更新时间:2023-01-24 13:24:20
使您的活动实现 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;
}
}