在Android里面,添加Listener,具体步骤如下:
1.首先在layout里面定义Button并指定响应的Listener
http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:text="Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClickH1"
/>
android:text="Button02"
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClick2"
/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
其中以下这两行就是新增的特性:
android:onClick="myClick1"
android:onClick="myClick2"
2.在活动里面定义public的方法myClick1、和myClick2
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class TestOnClickListener extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void myClickHandler01(View v){
setTitle("myClick1");
}
public void myClick2(View v){
setTitle("myClick2");
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class TestOnClickListener extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void myClick1(View v){
setTitle("myClick1");
}
public void myClick2(View v){
setTitle("myClick2");
}
}
也可以采用这种写法,将两个按钮设置到同一个Listener 代码如下所示:
android:onClick="onClick"
android:onClick="onClick"
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class TestOnClickListener extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void myClickHandler(View v){ switch (v.getId()) { case R.id.Button01: setTitle("Click1"); break; case R.id.Button2: setTitle("Click2"); break; } } }