你的意思是如果你点击按钮,你想改变按钮的背景颜色?是的,你可以做到
首先定义状态
private int btnState = 1;
private final static int BUTTON_STATE_SELECTED = 0;
private final static int BUTTON_STATE_UNSELECTED = 1;
然后将 id 设置为您的按钮
android:id="@+id/btnRoute"
android:background="@color/green"
android:drawableLeft="@drawable/custom_routes_start_button_icon"
android:text="@string/custom_route_start"
在您的活动中声明按钮
Button btnRoute = (Button) findviewbyid(R.id.btnRoute);
之后创建一个 onclick 侦听器,它将根据状态更改按钮颜色
private View.OnClickListener mOnClickBtnRoute = new View.OnClickListener() {
switch(btnState) {
case BUTTON_STATE_SELECTED:
btnRoute.setBackgroundColor(green);
btnRoute.setText(start);
Drawable img = getContext().getResources().getDrawable( R.drawable.custom_routes_start_button_icon );
btnRoute.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );
btnState = BUTTON_STATE_UNSELECTED;
break;
case BUTTON_STATE_UNSELECTED:
btnRoute.setBackgroundColor(red);
btnRoute.setText(stop);
Drawable img = getContext().getResources().getDrawable( R.drawable.custom_routes_stop_button_icon );
btnRoute.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );
btnState = BUTTON_STATE_SELECTED;
break;
}
};
然后不要忘记将侦听器设置为按钮
btnRoute.setOnClickListener(mOnClickBtnRoute);
请记住所有代码都在这里编码所以可能会有错误输入所以请不要只是复制粘贴而是尝试理解这个概念:) 如果您对我的回答有任何疑问,请随时在评论中提问!