很多点击事件,通过方法减少使用findViewbyid

1、

初学者可能会使用到,后期学习了ButterKnife就不会使用该方法了。学习一种思想

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="ceshi"
        android:text="按钮1" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="ceshi"
        android:text="按钮2" />
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="ceshi"
        android:text="按钮3" />
</LinearLayout>

2、

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ceshi(View v) {
switch (v.getId()) {
case R.id.button1:
Toast.makeText(getApplication(), "按钮1", 0).show();
break;
case R.id.button2:
Toast.makeText(getApplication(), "按钮2", 0).show();
break;
case R.id.button3:
Toast.makeText(getApplication(), "按钮3", 0).show();
break;
}
}


}

发布了56 篇原创文章 · 获赞 12 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/huwan12345/article/details/63249685