user1885484
user1885484

Reputation: 35

android | multiple onclicklistener in dialog

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" />

Upvotes: 0

Views: 906

Answers (2)

Bolton
Bolton

Reputation: 2256

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;
    }
}

Upvotes: 3

Antrromet
Antrromet

Reputation: 15414

  1. You should let your Activity/Fragment implement the OnClickListener.
  2. When you do that you will have to override the onClick method in that particular activity/fragment.
  3. Set the onClickListeners on the images as follows:

    img_1.setOnClickListener(YourActivity.this);
    
  4. Then in that onClick method you can put a switch case or an if else if case as follows

    @Override  
    public void onClick(View v)
    {   
        if(v==img_1) {  
              //do this  
        } else if(v==img_2) {  
            //do that  
        }...  
    }
    

    or

    @Override
    public void onClick(View v)
    {
        switch (v.getId()) {
            case img_1.getId(): // do this
                break;
            case img_2.getId(): // do that
                break;
            .
            .
            .
            default : break;
        }
    }
    

Upvotes: 0

Related Questions