2013-11-26 131 views
0

我想根據微調器中選定的值更改XML的顏色。這是我試過的代碼。如何使用微調器更改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方法,但它給了我錯誤

+1

你的'setBackground'方法在哪裏?你遇到了什麼錯誤? –

+0

「改變XML的顏色......」!這個問題聽起來不同... –

回答

0

確保XML具有相對的佈局,或任何主要佈局。在項目選定的呼叫,得到的佈局和使用的setBackground(getResources()。的getColor(R.color.color_name_here)。

希望有所幫助!

+0

謝謝。它工作,雖然我沒有必要調用getResource()。只是在setBackground我叫Color.color_name和它的工作。 –

0

獲得ID OG主佈局像

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

上飛旋的點擊

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

謝謝。有效。我不必調用getResource()。剛剛在setBackground()中使用了Color.color_name,它工作。 –

+0

很好,njy代碼 – Dev

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

}

+0

它的工作,但一旦顏色設置,然後它不會改變爲其他顏色時,我選擇其他值。 –

+0

if(color ==「Blue」) { 查看someView = findViewById(R.id.randomViewInMainLayout); //找到根視圖 視圖根= someView.getRootView() //設置顏色 root.setBackgroundColor(android.R.color.blue); }您是否寫過除紅色以外的其他情況? –

+0

是的,我做了,併爲每個案件,我已經給了不同的顏色 –