In my activity.xml I have a LinearLayout
. This LinearLayout
contains an inflated layout consisting of four ImageViews
. Implementation is something like this:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_template);
View view = getLayoutInflater().inflate(R.layout.inflated_layout, linearLayout, false);
linearLayout.addView(view);
I want to implement an action if the user clicks on the image. However, nothing happens when I click on the image. This is my implementation for onclick event:
v.getId()
gives me -1
every time I click an image
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("V.getID", String.valueOf(v.getId()));
Log.v("Image 1 id", String.valueOf(R.id.iv_t_1));
switch (v.getId()){
case R.id.iv_t_1: //image 1 clicked
//action
break;
case R.id.iv_t_2: //image 2 clicked
//action
break;
case R.id.iv_t_3: //image 3 clicked
//action
break;
case R.id.iv_t_4: //image 4 clicked
//action
break;
default:
break;
}
}
});
EDIT: The reason i don't want to set listeners on separate images is because the inflated layout is dynamic. It can contain any number from 1 to 4 images. If I have a layout of two images then the fourth imageView listener would return a nullptr exception
You can find those images and check if it's not null before setting
onClickListener
.