多个LinearLayout,怎么实现点击选中则变背景色,这里有一个很实用的方法

1.直接附上核心代码。

xml文件中现在有两个LinearLayout组件,每个LinearLayout中都有一个ImageButton和TextView,现在让每个LinearLayout加上点击事件。

android:onClick="changeBackground"

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_weight="1"
    android:onClick="changeBackground"
    android:id="@+id/device">
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/devicea"
        android:scaleType="fitXY"
        android:background="#e0000000"
        android:layout_marginTop="5dp"
        android:clickable="false"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="2dp"
        android:textColor="#808080"
        android:text="设备"/>
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_weight="1"
    android:clickable="true"
    android:onClick="changeBackground"
    android:id="@+id/loca">
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/locaa"
        android:scaleType="fitXY"
        android:background="#e0000000"
        android:layout_marginTop="5dp"
        android:clickable="false"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="0dp"
        android:textColor="#808080"
        android:text="定位"/>
</LinearLayout>

2.在MainActivity中写点击触发事件

View temp;
public void changeBackground(View v){
    if(temp == null)temp = v;
    if(!(temp == v)){
        temp.setBackgroundColor(Color.BLACK);
    }
    v.setBackgroundColor(Color.GRAY);
    temp = v;
}

第一个if是给temp临时对象赋初值。第二个if是判断点击的组件是不是自己,不是的话,自己的背景就回复为黑色;设置点击到的组件背景变为灰色。

是不是很简单啊!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值