我建立一个Android应用程序。我注意到,我创建了code多次重复在我的每个类与此类似:
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}
}
});
我现在有15个按键,这是使我的code难看。有没有人有一个类或一些例子,我怎么可以把所有这些codeS为更有效的,这样我就可以:
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:
创建按钮OBJ {按钮buttonX(按钮)findViewById(R.id.buttonXName);} 设置监听{buttonX.setOnClickListener(新OnClickListener()} 确定它是否被点击{公共无效的onClick(视图v)} 然后运行特定的code为每个按钮?如果有人知道任何事情,我倒是AP preciate吧。
If anyone knows anything, I'd appreciate it.
如果你的目标1.6或更高版本,可以使用的安卓的onClick XML属性去除一些重复的code。请参见这个博客帖子通过罗曼盖伊。
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类,使用这些低于code线:
And in the Java class, use these below lines of code:
class MyActivity extends Activity {
public void myClickHandler(View target) {
// Do stuff
}
}
上一篇:在Eclipse Android框架的调试框架、Eclipse、Android
下一篇:Android的WebKit的:绝对定位的元素不尊重的z-index素不、Android、WebKit、index