【问题标题】:How to change background color of xml by using spinner如何使用微调器更改 xml 的背景颜色
【发布时间】:2013-11-26 17:16:36
【问题描述】:

我想根据微调器中选择的值更改 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 方法,但它给了我错误

【问题讨论】:

  • 您的setBackground 方法在哪里?你遇到了什么错误?
  • "改变 XML 的颜色..." !!这个问题听起来不一样……

标签: android xml spinner


【解决方案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);
  }

}

【讨论】:

  • 它有效,但是一旦设置了颜色,当我选择其他值时它不会变为其他颜色。
  • if(color=="Blue") { 查看 someView = findViewById(R.id.randomViewInMainLayout); // 找到根视图 View root = someView.getRootView() // 设置颜色 root.setBackgroundColor(android.R.color.blue); } 你写过 Red 以外的其他案例吗?
  • 试试这个代替 android.R.color.red, root.setBackgroundColor(Color.RED);在我的情况下它工作得很好
  • 如果你还没有完全理解,那么我将分享我的代码。
【解决方案2】:

确保 xml 具有相对布局或任何主布局。在 Item selected call 中,获取布局并使用 setbackground(getResources().getColor(R.color.color_name_here)。

希望对您有所帮助!

【讨论】:

  • 谢谢。尽管我不必调用 getResource(),但它仍然有效。就在 setBackground 我调用了 Color.color_name 并且它起作用了。
【解决方案3】:

获取您的主要布局的 id,例如

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

点击微调器

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

【讨论】:

  • 谢谢。有效。我不必调用 getResource()。刚刚在 setBackground() 中使用了 Color.color_name 并且它起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多