简体   繁体   English

如何使用微调框更改xml的背景色

[英]How to change background color of xml by using spinner

I want to change the color of XML based on the value selected in the spinner. 我想根据微调器中选择的值来更改XML的颜色。 Here is the code that i had tried. 这是我尝试过的代码。

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")
    {

    }
}



}

Iam trying to use setBackground method but it gives me error 我试图使用setBackground方法,但它给我错误

Try below code! 试试下面的代码!

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);
  }

} }

Make sure the xml has a relative layout, or any main layout. 确保xml具有相对布局或任何主布局。 On Item selected call, get the layout, and use setbackground(getResources().getColor(R.color.color_name_here). 在“选定项目”调用上,获取布局,然后使用setbackground(getResources()。getColor(R.color.color_name_here)。

Hope that helps.! 希望有帮助!

get the id og your main layout like 得到你的主要布局的ID和

    Yourlayout(linear or realtive) layout = (Yourlayout)findviewbyid(R.id.yourlayoutid);

on on click of spinner 点击微调器

 if(color=="Red")
   {
    layout.setbackground(getResources().getColor(R.color.color_name_here);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM