Home » Android » android – how to set onClick method with linearLayout?

android – how to set onClick method with linearLayout?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am creating an application and posted a question yesterday
how to start activity by click any where on row.
Got an idea to do like below but I am getting this error:

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new OnClickListener(){})

Here is my code:

LinearLayout menu_photos = (LinearLayout )findViewById(R.id.picture_part);
menu_photos.setOnClickListener(new OnClickListener() {      
    @Override
    public void onClick(View v) {
        Intent picture_intent = new Intent(CurrentActivity.this,PictureActivity.class);
        startActivity(picture_intent );     
    }
});

XML:

How to&Answers:

below line is ur code:-

replace this line to below code:-

Answer:

set LinearLayout attribute android:clickable="true"
if you have any button or textview in layout set android:clickable="false" for all of them

Answer:

From your xml layout file i think what you are looking for is a listview, not loads of linearlayouts. Here is nice tutorial to get you started, might be exactly what you need, row with image and text. For the listview just use setOnItemCLickListener().

Back to what you want, I think you need to make the linearlayout focusable/touchable in order to “receive” clicks.

Answer:

Great catch by @duggu.
Apart from the answer, using ImageView and TextView inside a LinearLayout, nesting LinearLayout is a bad idea. Instead use drawableLeft:@src of a TextView and also for a divider you can use a simple View instead of inflating a drawable.