效果:
点击前:
点击中:
布局文件中代码:
... <LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="60dip" android:orientation="vertical" android:clickable="true"> <TextView android:textSize="20sp" android:gravity="center" android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="match_parent" android:text="按钮"/> </LinearLayout> ...
在代码中设置这些颜色:
... @Override protected void onCreate(Bundle savedInstanceState) { ... LinearLayout layout = (LinearLayout) findViewById(R.id.layout); TextView textView = (TextView) findViewById(R.id.textView); setPressedBg(layout,"#00ffff","#00ff00","#00ff00"); setTextPressedBg(textView,"#000000","#ffffff","#ffffff"); textView.setDuplicateParentStateEnabled(true); //子视图与父控件perssed 等状态保持一致 } /** * 设置单击背景色 * @param view 控件 * @param normal 未选择时的背景色 * @param focused 选择时的背景色 * @param pressed 选择时的背景色 */ public void setPressedBg(View view, String normal,String focused, String pressed) { int[][] states = new int[6][]; states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; states[2] = new int[] { android.R.attr.state_enabled }; states[3] = new int[] { android.R.attr.state_focused ,android.R.attr.state_window_focused}; states[4] = new int[] { android.R.attr.state_window_focused }; StateListDrawable bg = new StateListDrawable(); bg.addState(states[0], new ColorDrawable(Color.parseColor(pressed))); bg.addState(states[3], new ColorDrawable(Color.parseColor(focused))); bg.addState(states[2], new ColorDrawable(Color.parseColor(normal))); view.setBackground(bg); } /** * 对TextView设置不同状态时其文字颜色。 * @param textView 控件 * @param normal 未选择时的文字颜色 * @param pressed 选择时的文字颜色 * @param focused 选择时的文字颜色 */ private void setTextPressedBg(TextView textView,String normal, String pressed, String focused) { int[][] states = new int[6][]; states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; states[2] = new int[] { android.R.attr.state_enabled }; states[3] = new int[] { android.R.attr.state_focused }; states[4] = new int[] { android.R.attr.state_window_focused }; states[5] = new int[] {}; int normalColor = Color.parseColor(normal); int pressedColor = Color.parseColor(pressed); int focusedColor = Color.parseColor(focused); ColorStateList colorList = new ColorStateList(states, new int[] {pressedColor,focusedColor,normalColor,focusedColor,focusedColor,normalColor}); textView.setTextColor(colorList); } ...