Android Button setOnClickListener设计 [英] Android Button setOnClickListener Design

查看:129
本文介绍了Android Button setOnClickListener设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Android应用程序.我注意到我在每个类中都创建了许多与此类似的重复代码:

I am building an Android Application. I've noticed that I am creating many repetitions of code similar to this in each of my classes:

Button buttonX = (Button)findViewById(R.id.buttonXName);
// Register the onClick listener with the implementation above
buttonX.setOnClickListener(new OnClickListener() {
    public void onClick(View v)
    {
        //DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
    } 
});

我现在有15个按钮,这使我的代码很难看.有没有人提供有关如何将所有这些代码转换为更有效的内容的课程或示例,所以我可以:

I now have fifteen buttons and this is making my code ugly. Does anyone have a class or some examples on how I can turn all these codes into something more efficient, so I can:

  1. 创建按钮对象{Button buttonX (Button)findViewById(R.id.buttonXName);}
  2. 设置监听器{buttonX.setOnClickListener(new OnClickListener()}
  3. 确定是否单击了{public void onClick(View v)}
  4. 然后为每个按钮运行特定的代码吗?
  1. Create the button object {Button buttonX (Button)findViewById(R.id.buttonXName);}
  2. Set the listener {buttonX.setOnClickListener(new OnClickListener()}
  3. Determine if it was clicked {public void onClick(View v)}
  4. Then run specific code for each button?

如果有人知道什么,我将不胜感激.

If anyone knows anything, I'd appreciate it.

推荐答案

如果您的目标是1.6或更高版本,则可以使用此博客文章,作者:罗曼·盖伊.

If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.

<Button 
   android:height="wrap_content"
   android:width="wrap_content"
   android:onClick="myClickHandler" />

在Java类中,使用以下几行代码:

And in the Java class, use these below lines of code:

class MyActivity extends Activity {
    public void myClickHandler(View target) {
        // Do stuff
    }
}

这篇关于Android Button setOnClickListener设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆