Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make linear layout selectable like a list item in a list view (Android)

Tags:

I know how to add an onClick listener to a LinearLayout to make the whole layout a click target, but I'd like to have the LinearLayout get highlighted when tapped just like a list item in a list view. What's the best way to do this?

like image 948
MobileDev852 Avatar asked Apr 28 '11 15:04

MobileDev852


People also ask

How do I make a list view clickable?

Add 'type'=>'name', and 'link'=>true, to the array for the field, which will override the stock field's vardef and make the field clickable.

Can we use linear layout in RelativeLayout inside?

We can use LinearLayout inside RelativeLayout. We can also use RelativeLayout as a Child of LinearLayout.

How to get data from ListView by clicking item on ListView?

Try this: my_listview. setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } });

Can we use linear layout in ConstraintLayout?

You can create linear layouts now with ConstraintLayout by constraining the sides of each element with each other. The quick way of creating these layouts is to select all the views together and right click to center horizontally or vertically.


2 Answers

I prefer a simpler way:

<LinearLayout android:orientation="vertical"               android:id="@+id/layoutIdentifier"               android:clickable="true"               android:background="?android:attr/selectableItemBackground"                android:layout_width="match_parent"               android:layout_height="match_parent">      <!-- put views here --> </LinearLayout> 

You can't change the state-pressed background this way, but sometimes you don't really need to.

like image 180
Blacklight Avatar answered Oct 19 '22 23:10

Blacklight


I ran into this and this is what I came up with. In your layout, set the background to a drawable resource:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:id="@+id/clickable_layout"     android:layout_width="fill_parent"      android:layout_height="wrap_content"     android:background="@drawable/clickable">  ... </LinearLayout> 

Then in drawable, add clickable.xml as so:

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"     android:drawable="@android:drawable/list_selector_background" />       </selector> 

Then it's up to you whether or not you want to add a click handler in your activity.

like image 20
Jerry Brady Avatar answered Oct 20 '22 01:10

Jerry Brady