I haven't tried it, but you can possibly set the LinearLayout's android:background to this selector, and set android:clickable to true and it'll work.
If it doesn't, you could switch to using a RelativeLayout, and make the first element a button with this selector as the background and fill_parent for its layout width and height. In this case, just use a regular Button and set android:background to your selector. You don't have to put text on your button.
In the application I am working I need to create a LinearLayout dynamically. In this case the command
ll.setClickable(true);
is not working as supposed to do. Although I may miss something, I managed to exploit setOnTouchListener to get the same result and I submit the code in case anyone has the same needs.
The following code creates a LinearLayout with two textviews and round corners, changing color when pressed.
First, create two xml files in drawable folder, one for normal and one for pressed linearlayout state.
Normal state xml (drawable/rounded_edges_normal.xml)
// Create some textviews to put into the linear layout...
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
tv1.setText("First Line");
tv2.setText("Second Line");
// LinearLayout definition and some layout properties...
final LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
// it is supposed that the linear layout will be in a table.
// if this is not the case for you change next line appropriately...
ll.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ll.setBackgroundResource(R.drawable.rounded_edges_normal);
ll.addView(tv1);
ll.addView(tv2);
ll.setPadding(10, 10, 10, 10);
// Now define the three button cases
ll.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction()==MotionEvent.ACTION_DOWN){
ll.setBackgroundResource(R.drawable.rounded_edges_pressed);
ll.setPadding(10, 10, 10, 10);
layoutpressed = arg0.getId();
}
else if (arg1.getAction()== MotionEvent.ACTION_UP){
ll.setBackgroundResource(R.drawable.rounded_edges_normal);
ll.setPadding(10, 10, 10, 10);
if(layoutpressed == arg0.getId()){
// ...........................................................................
// Code to execute when LinearLayout is pressed...
// ...........................................................................
}
}
else{
ll.setBackgroundResource(R.drawable.rounded_edges_showtmimata);
ll.setPadding(10, 10, 10, 10);
layoutpressed = -1;
}
return true;
}
});
This was helpful but if you want to put a background color and make linear layout clickable like the list item. Set the background with your preferred color and set foreground color to ?android:attr/selectableItemBackground, set focusable true, and clickable true