2016-07-07 61 views
-3

嗨我正在做一個學校項目,我正在做一個性別分類。如果我選擇男性,男性圖標應加載到我的android應用程序中的imageView和Vice Versa。如何選擇單選按鈕將圖像加載到imageView

public static TextView lable5,lable7; 
public static SeekBar SB1,SB2; 
public static RadioButton RB1,RB2; 
public static ImageView IV1; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_layout); 

    lable5 = (TextView) findViewById(R.id.textView5); //this is for seekbar1 
    lable7 = (TextView) findViewById(R.id.textView7); //This is for seekbar2 
    RB1 = (RadioButton) findViewById(R.id.radioButton1); // This is for male option 
    RB2 = (RadioButton) findViewById(R.id.radioButton2); // This is for Female Option 
    IV1 = (ImageView) findViewById(R.id.imageView); // This is the only imageView available 


    SB1=(SeekBar) findViewById(R.id.seekBar1);// This is for seekBar1 
    SB2=(SeekBar) findViewById(R.id.seekBar2);//This is for seekBar2 
    lable5.setText(String.valueOf(SB1.getProgress())); 
} 
+2

你到目前爲止做了什麼?告訴我們你的代碼。 – SripadRaj

+0

歡迎來到StackOverflow。請閱讀[如何提出一個好問題。](http://stackoverflow.com/help/how-to-ask)並注意:Java和JavaScript是獨立的語言。 – nnnnnn

+0

以上顯示 –

回答

0

假設你添加的單選按鈕在RadioGroup你可以做到以下幾點:

group = (RadioGroup) findViewById(R.id.radioGroup); 
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
    @Override 
    public void onCheckedChanged(RadioGroup group, int checkedId) { 
    switch(checkedId) { 
     case R.id.radioButton1: 
     IV1.setImageResource(R.drawable.male_icon); 
     break; 
     case R.id.radioButton2: 
     IV1.setImageResource(R.drawable.female_icon); 
     break; 
     default: 
     break; 
    } 
    } 
}); 

如果你的單選按鈕在RadioGroup你可以用這樣的代碼添加他們:

<RadioGroup 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radioGroup" > 
    <RadioButton ... /> 
    <RadioButton ... /> 
</RadioGroup> 

如果您在使用我的代碼時遇到問題,請發表評論,我會幫您。

+0

這是在廣播組,我得到一個錯誤,說int不能轉換爲Drawable –

+0

我的壞。對於那個很抱歉!我更新了答案,它現在應該可以工作。問題是我使用了'setImageDrawable',它有一個'Drawable'參數,我發送了一個'int'。使用'setImageResource'你可以通過它的id來設置圖像。 –

+0

謝謝這是工作的晶圓廠:D –