I have multiple linear layouts inside a ScrollView
.Each linear layout
have a image on click of which i want to set the linear layout background as selected as we have in listview
.
XML
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<ImageView
android:id="@+id/img1"
android:layout_width="90dp"
android:layout_height="50dp"
android:background="@mipmap/ic_launcher"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:id="@+id/layout2"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<ImageView
android:id="@+id/img2"
android:layout_width="90dp"
android:layout_height="50dp"
android:background="@mipmap/ic_launcher"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:id="@+id/layout3"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<ImageView
android:id="@+id/img3"
android:layout_width="90dp"
android:layout_height="50dp"
android:background="@mipmap/ic_launcher"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:id="@+id/layout4"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<ImageView
android:id="@+id/img4"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="@mipmap/ic_launcher" />
</LinearLayout>
</ScrollView>
I have done like this onclick of the imageView:
layout1.setBackgroundColor(Color.BLUE);
But this is not giving me the desired output .Please help me in this how we can do this
change the selected State :
public void changeState(){
for (int i = 0; i < mainLayout.getChildCount(); i++) {
View child = mainLayout.getChildAt(i);
child.setSelected(false);
}
}
Create a xml drawable in your drawable folder ex:
background_linear.xml
write the below codeThen set
background_linear
as background for yourLinearLayout
in your xml layout.And on click of image view call this method
layout1.setSelected(true);
To remove the selection you have to call same method by passing
false
. If you have multipleLinearLayout
then you should remember which one was previously selected layout. To achieve this you can do this: Define anint
to storeid
of the previously selected view.And in on click of image view
If you don't want set
ClickListener
to everyImageView
in java then setonClick
property of allImageView
in xml to same method.