public class MainActivity extends Activity implements View.OnClickListener { private TextView Txt; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); InitView(); } private void InitView(){ Txt= (TextView) findViewById(R.id.textView); btn= (Button) findViewById(R.id.button1); btn.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.button1: Txt.setText("Hello!"); break; } } }
说明:加入代码片段implements View.OnClickListener,在MainActivity上按Alt+Enter,点击implement class,会自动生成重写方法onClick(View v),然后将点击事件放在初始化函数InitView()中,注意参数是this。
时间: 2024-10-27 00:01:30