从零开始学android开发-View的setOnClickListener的添加方法
1)第一种,也是最长见的添加方法(一下都以Button为例)
Button btn = (Button) findViewById(R.id.myButton); btn .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //do something } });
2)第二种,下面这个方法较前一种稍微简单了一些,允许多个Buttons共享一个Listener。通过Switch控制对不同Button Click事件的响应方法:
Button btn = (Button) findViewById(R.id.mybutton); Button btn2 = (Button) findViewById(R.id.mybutton2); btn.setOnClickListener(handler); btn2.setOnClickListener(handler); View.OnClickListener handler = View.OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.mybutton: //do something break; case R.id.mybutton2: //do something break; } }
或者
Button list=null; Button about=null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); list=(Button)findViewById(R.id.foodlistbtn); about=(Button)findViewById(R.id.aboutbutton); // list.setText(text); // list.setCompoundDrawables(left, top, right, bottom); list.setOnClickListener(this); about.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.getId()==R.id.foodlistbtn){ Intent intent=new Intent(); intent.setClass(MainApp.this, FoodListView.class); startActivity(intent); list.setBackgroundResource(R.drawable.btn_food_list_active); }else if(v.getId()==R.id.aboutbutton){ Intent intent=new Intent(this, About.class); startActivity(intent); about.setBackgroundResource(R.drawable.btn_food_about_active); } }
3)第三种,直接将Clicklistener捆绑XML layout中的Views元素,在程序中定义的Listener方法需要带有一个View类型的参数:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/text" android:text="@string/hello" /> <Button android:id="@+id/mybutton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="mybuttonlistener"></Button> </LinearLayout>
java代码:
Button btn = (Button) findViewById(R.id.mybutton); public void mybuttonlistener(View target){ //do something }