Android Button setOnClickListener设计帮助 [英] Android Button setOnClickListener Design Help
问题描述
Button buttonX =(Button) findViewById(R.id.buttonXName);
//注册onClick监听器,执行上面
buttonX.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
// DO SOMETHING!{运行某些功能...检查...等等}
}
});
我现在有15个按钮,这使我的代码丑陋。有没有人有一个类或一些例子,关于我如何将所有这些代码变成更有效率的东西,所以我可以:
- 创建按钮OBJ {Button buttonX(Button)findViewById(R.id.buttonXName);}
- 设置侦听器{buttonX.setOnClickListener(new OnClickListener()}
- 确定是否被点击{public void onClick(View v)}
- 然后为每个按钮运行特定代码?
如果有任何人知道任何事情,我会很感激。
1.6或更高版本,您可以使用 android:onClick xml属性删除一些重复代码。请参阅这个博客由Romain Guy。
< Button
和roid:height =wrap_content
android:width =wrap_content
android:onClick =myClickHandler/>
在Java类中,使用以下代码行:
class MyActivity extends Activity {
public void myClickHandler(View target){
// Do stuff
}
}
I am building an Android Application. I've noticed 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}
}
});
I now have 15 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:
- Create the button OBJ {Button buttonX (Button)findViewById(R.id.buttonXName);}
- Set the listener {buttonX.setOnClickListener(new OnClickListener()}
- Determine if it was clicked {public void onClick(View v)}
- Then run specific code for each button?
If anyone knows anything, I'd appreciate it.
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" />
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屋!