我想根据微调器中选择的值更改XML的颜色。这是我尝试过的代码。
public class MainActivity extends Activity implements OnItemClickListener{
Spinner obj;
String[] str={"Red","Green","Yellow","Gray"};
ArrayAdapter<String> adapter;
ViewGroup vg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obj=(Spinner)findViewById(R.id.spinner);
vg=(ViewGroup)findViewById(R.id.relative);
adapter=new ArrayAdapter<String>(getBaseContext(),android.R.
layout.simple_dropdown_item_1line,str);
obj.setAdapter(adapter);
obj.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String color=obj.getSelectedItem().toString();
if(color=="Red")
{
}
}
}
我试图使用setBackground方法,但它给了我错误
答案 0 :(得分:1)
尝试以下代码!
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String color=str[arg2]; //where arg2 is position of selected item
if(color=="Red")
{
View someView = findViewById(R.id.randomViewInMainLayout);
// Find the root view
View root = someView.getRootView()
// Set the color
root.setBackgroundColor(Color.RED);
}
}
答案 1 :(得分:0)
确保xml具有相对布局或任何主布局。在Item选择的调用中,获取布局,并使用setbackground(getResources()。getColor(R.color.color_name_here)。
希望有所帮助。!
答案 2 :(得分:0)
获取主要布局的ID,如
Yourlayout(linear or realtive) layout = (Yourlayout)findviewbyid(R.id.yourlayoutid);
单击微调器
if(color=="Red")
{
layout.setbackground(getResources().getColor(R.color.color_name_here);
}