android |对话框中的多个onclicklistener [英] android | multiple onclicklistener in dialog
问题描述
在我的活动中我开始一个简单的对话框。
final Dialog myDialog = new Dialog(this);
myDialog.setContentView(R.layout.testing);
...
我的test.xml布局只有10个ImageViews,id` s是'1'到'10'。
我希望每个ImageView都可以点击并做某事。
定义.xml文件中的onclick()方法不工作,因为在查看对话框时找不到方法。
我唯一的方法是工作如下:定义10个onclick-listeners:
ImageView img_1 =(ImageView)myDialog.findViewById R.id.1);
ImageView img_2 =(ImageView)myDialog.findViewById(R.id.2);
...
img_1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view){
execute_funtion(1) ;
myDialog.cancel();
}
});
img_2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view){
execute_funtion(2);
myDialog。 cancel();
}
});
...
然而,这是非常糟糕的代码,我有10时间几乎相同。
所以我的问题:如何使用干净的代码进行工作?
我想到了一个多重onclicklistener(覆盖onClick()函数,并在函数或类似的东西中做一个switch / case),但它不工作。
<我对每一个想法感到高兴!
谢谢
/ EDIT
这里是.xml文件的一个片段
< ImageView
android:id =@ + id / 1
android:layout_width =wrap_content
android:layout_height =wrap_content
android:padding =2dp
android:onClick =myFunction
android:src =@ drawable / ic_launcher/>
使您的活动实现 OnClickListener
,然后处理 onClick
事件,如下所示:
@Override
public void onClick(View v){
switch(v.getId()){
case R.id.img1:
...
休息
case R.id.img2:
...
break;
}
}
Inside my Activity I start a simple dialog.
final Dialog myDialog = new Dialog(this);
myDialog.setContentView(R.layout.testing);
...
My testing.xml Layout consists of nothing but 10 ImageViews, id`s are '1' to '10'.
I want every ImageView to be clickable and to do something. The define the onclick() methode in the .xml file isn`t working, as the methode can't be found when the dialog is viewed.
The only way I got it work is following: define 10 onclick-listeners:
ImageView img_1 = (ImageView) myDialog.findViewById(R.id.1);
ImageView img_2 = (ImageView) myDialog.findViewById(R.id.2);
...
img_1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
execute_funtion(1);
myDialog.cancel();
}
});
img_2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
execute_funtion(2);
myDialog.cancel();
}
});
...
However, that's really bad code, I have 10 times nearly the same lines.
So my question: How can I make that work with clean code? I thought about a multiple onclicklistener (overwride the onClick() function and make a switch/case in the functions or something like that), but it's not working.
I'm happy about every idea! Thanks
/EDIT
Here a snippet of the .xml file
<ImageView
android:id="@+id/1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:onClick="myFunction"
android:src="@drawable/ic_launcher" />
Make your Activity implement OnClickListener
and then process the onClick
event like below:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img1:
...
break;
case R.id.img2:
...
break;
}
}
这篇关于android |对话框中的多个onclicklistener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!