最近做的项目里需要用到layout点击事件,其实非常简单,只要为需要点击的layout设置一个id,并像按钮一样调用就行了
public class youqing extends Activity {
private LinearLayout youqing1,youqing2,youqing3,youqing4,youqing5,youqing6,youqing7,youqing8;
private ImageButton back1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youqing);
youqing1 = (LinearLayout) findViewById(R.id.youqing1);
youqing2 = (LinearLayout) findViewById(R.id.youqing2);
youqing3 = (LinearLayout) findViewById(R.id.youqing3);
youqing4 = (LinearLayout) findViewById(R.id.youqing4);
youqing5 = (LinearLayout) findViewById(R.id.youqing5);
youqing6 = (LinearLayout) findViewById(R.id.youqing6);
youqing7 = (LinearLayout) findViewById(R.id.youqing7);
youqing8 = (LinearLayout) findViewById(R.id.youqing8);
back1 = (ImageButton) findViewById(R.id.back1);
youqing1.setOnClickListener(new onclicklistener());
youqing2.setOnClickListener(new onclicklistener());
youqing3.setOnClickListener(new onclicklistener());
youqing4.setOnClickListener(new onclicklistener());
youqing5.setOnClickListener(new onclicklistener());
youqing6.setOnClickListener(new onclicklistener());
youqing7.setOnClickListener(new onclicklistener());
youqing8.setOnClickListener(new onclicklistener());
back1.setOnClickListener(new onclicklistener());
}
}
但是太多个点击区域就会使点击事件设置得频繁,当需要做的事情重复发生时,我们就可以使用面向对象的方法来解决问题,把点击事件的动作封装成一个工具类,需要的使用直接调用传入参数即可
public class onclicklistener implements OnClickListener { /*页面跳转函数*/public static void showActivity(Context context,Class> cls){Intent intent =new Intent(context,cls);context.startActivity(intent);}@Overridepublic void onClick(View v) {Context context = v.getContext();switch(v.getId()){case R.id.jieshu:/*showActivity(context, jieshu.class);*/break;case R.id.dianzi:Toast toast = Toast.makeText(context, "显示一个出现在屏幕中央的Toast", Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER, 0, 0);toast.show();break;case R.id.back:((Activity) context).finish(); /*实现返回功能*/}}}