当我从微调器列表中选择颜色时,我想更改应用程序的背景颜色。但我找不到实现这一目标的方法。有谁能建议解决这个问题?我的代码如下:
SpinnerActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this,R.array.colors,R.layout.dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Toast.makeText(parent.getContext(),
"The color is" + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
主
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#000"
tools:context=".SpinnerActivity">
<TextView
android:text="Pick a Color.Any Color."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:id="@+id/textView" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:layout_marginTop="29dp"
android:layout_below="@+id/textView"
android:background="#fff"
/>
string
<resources>
<string name="app_name">UISpinner</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="colors">
<item>red</item>
<item>yellow</item>
<item>orange</item>
<item>blue</item>
<item>green</item>
<item>white</item>
<item>pink</item>
</string-array>
答案 0 :(得分:1)
您可以尝试使用RelativeLayout
RelativeLayout relativeLayout = findViewById(R.id.relative_layout) //note you actuall need to set the id in your xml as well
然后在你的微调器的onItemSelect中
relativeLayout.setBackgroundColor(Color.GRAY);
这真的很简单,因为它只朝一个方向发展。如果你想切换它,请查看设置布尔标志。