使用单选按钮更改背景颜色
作者:互联网
我试图通过从RadioGroup中选择一个单选按钮来更改应用程序选项卡的背景,但是我不确定如何执行此操作.
到目前为止,我有
Favs.java:
import android.app.Activity;
import android.os.Bundle;
public class Favs extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favs);
}
}
指向此.xml文件-> favs.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is your favorite color?"
android:padding="3dip"/>
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:onClick="onClick" />
<RadioButton android:id="@+id/radio_yellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow" />
</RadioGroup>
</LinearLayout>
我了解android:onClick =“ onClick”必须存在,但是我不知道此后该怎么做.
解决方法:
您好使用以下代码根据单选按钮的选择更改背景
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
android:orientation="vertical"
android:id="@+id/LinearLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is your favorite color?"
android:padding="3dip"/>
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/Group1"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
/>
<RadioButton android:id="@+id/radio_yellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow" />
</RadioGroup>
</LinearLayout>
活动
public class Change extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout ll=(LinearLayout) findViewById(R.id.LinearLayout);
final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red);
final RadioButton radio_yellow = (RadioButton) findViewById(R.id.radio_yellow);
radio_red.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ll.setBackgroundColor(Color.RED);
}
});
radio_yellow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ll.setBackgroundColor(Color.YELLOW);
}
});
}
}
标签:background,onclick,radio-group,android 来源: https://codeday.me/bug/20191023/1914086.html