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是判断点击的组件是不是自己,不是的话,自己的背景就回复为黑色;设置点击到的组件背景变为灰色。
是不是很简单啊!!!!