android – 做一个可以独立选择和激活的按钮组的最佳方法是什么?
作者:互联网
我试图在android中做一组可以选择的按钮,只激活其中一个按钮.我需要使用与radiogroup和radiobuttons相同的逻辑.
我尝试了很多替代方案,但我想要最有效的方法.我该怎么做?
解决方法:
您可以使用这种简单的方法:
1.activity_button_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
android:id="@+id/btn0"
android:layout_gravity="center_vertical" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B"
android:id="@+id/btn1"
android:layout_gravity="center_vertical" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:id="@+id/btn2"
android:layout_gravity="center_vertical" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="D"
android:id="@+id/btn3"
android:layout_gravity="center_vertical" />
</LinearLayout>
2.ButtonGroupActivity.java
public class ButtonGroupActivity extends Activity implements View.OnClickListener{
private Button[] btn = new Button[4];
private Button btn_unfocus;
private int[] btn_id = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_group);
for(int i = 0; i < btn.length; i++){
btn[i] = (Button) findViewById(btn_id[i]);
btn[i].setBackgroundColor(Color.rgb(207, 207, 207));
btn[i].setOnClickListener(this);
}
btn_unfocus = btn[0];
}
@Override
public void onClick(View v) {
//setForcus(btn_unfocus, (Button) findViewById(v.getId()));
//Or use switch
switch (v.getId()){
case R.id.btn0 :
setFocus(btn_unfocus, btn[0]);
break;
case R.id.btn1 :
setFocus(btn_unfocus, btn[1]);
break;
case R.id.btn2 :
setFocus(btn_unfocus, btn[2]);
break;
case R.id.btn3 :
setFocus(btn_unfocus, btn[3]);
break;
}
}
private void setFocus(Button btn_unfocus, Button btn_focus){
btn_unfocus.setTextColor(Color.rgb(49, 50, 51));
btn_unfocus.setBackgroundColor(Color.rgb(207, 207, 207));
btn_focus.setTextColor(Color.rgb(255, 255, 255));
btn_focus.setBackgroundColor(Color.rgb(3, 106, 150));
this.btn_unfocus = btn_focus;
}
}
标签:android,android-button 来源: https://codeday.me/bug/20191006/1860283.html