<第一種用法>在xml裡設定android:onClick
<main.xml>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doActivity"/>
<MainActivity.java>
public void doActivity(View view) {
Intent intent=new Intent();
intent.setClass(this,Second.class);
//法一:
Bundle bundle =new Bundle();
bundle.putString("name", "Wei");
intent.putExtras(bundle);
//法二:
//intent.putExtra("name", "Chen");
this.startActivity(intent);
}
就完成了buttion onClick的設定了
<第二種用法> 多個buttion各有其用途
Button button1=(Button) this.findViewById(R.id.button1);
button1.setText(name);
button1.setOnClickListener(this);
Button button2=(Button) this.findViewById(R.id.button2);
button2.setOnClickListener(this);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
Toast.makeText(this, "Buttion1",Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(this, "Buttion2",Toast.LENGTH_SHORT).show();
break;
}
}
<第三種用法>
Button button3=(Button) this.findViewById(R.id.button3);
button3.setOnClickListener(new Foo());
public class Foo implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Second.this, "upper right",Toast.LENGTH_SHORT).show();
}
}
<第四種用法>匿名內部類別註冊
Button button4=(Button) this.findViewById(R.id.button4);
button4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Second.this, "Buttion4",Toast.LENGTH_SHORT).show();
}
});
沒有留言:
張貼留言