转载请注明出处:/u014657752/article/details/47294213
总结一下Button 点击事件onclick实现的四种方式;
方式一:
在xml中定义onclick属性
-
<span style="white-space:pre"> </span><Button
-
android:id="@+id/button1"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:layout_gravity="center_horizontal"
-
android:onClick="onclick_button1"
-
android:text="方式一" />
-
<span style="white-space:pre"> </span>// 方式一
-
public void onclick_button1(View view) {
-
(this, "方式一", Toast.LENGTH_SHORT).show();
-
}
方式二:
匿名内部类
-
button2 = (Button) findViewById(.button2);
-
(new OnClickListener() {
-
@Override
-
public void onClick(View v) {
-
(MainActivity.this, "方式二", Toast.LENGTH_SHORT)
-
.show();
-
}
-
});
创建内部类实现OnClickListener接口
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(.activity_main);
-
-
button3 = (Button) findViewById(.button3);
-
(new Button3());
-
}
-
-
<span style="white-space:pre"> </span>// 方式三
-
public class Button3 implements OnClickListener {
-
-
@Override
-
public void onClick(View v) {
-
(MainActivity.this, "方式三", Toast.LENGTH_SHORT).show();
-
}
-
-
}
方式四:
Activity实现OnClickListener接口
-
public class MainActivity extends Activity implements OnClickListener {
-
-
Button button4;
-
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(.activity_main);
-
-
button4 = (Button) findViewById(.button4);
-
(this);
-
}
-
-
@Override
-
public void onClick(View v) {
-
switch (()) {
-
case .button4:
-
(MainActivity.this, "方式四", Toast.LENGTH_SHORT).show();
-
break;
-
default:
-
break;
-
}
-
}
-
}
Email:yu_longji@
****:/u014657752