當(dāng)前位置:首頁 > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > Button監(jiān)聽器的五種方式
第一種:內(nèi)部類的方式
class MyButton implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "我被點(diǎn)擊了!", Toast.LENGTH_SHORT).show();
}
}
第二種:匿名內(nèi)部類的方式
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "我又被點(diǎn)擊了!", Toast.LENGTH_SHORT).show();
}
});
第三種:外部類方式
public class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("我第四次被點(diǎn)擊了!");
}
}
.........................................
MyOnClickListener clickListener = new MyOnClickListener();
button.setOnClickListener(clickListener);*/
第四種:Activity本身方式
public class MainActivity extends Activity implements OnClickListener {
.......................
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(, "我第四次被點(diǎn)擊了!", Toast.LENGTH_SHORT).show();
}
...............................
}
第五種:綁定標(biāo)簽
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:onClick="MyListener"
/>
在Activity中實(shí)現(xiàn)方法MyListener()
public void MyListener(View view)
{
Toast.makeText(MainActivity.this, "我第五次被點(diǎn)擊了!", Toast.LENGTH_SHORT).show();
}