如果选择单选按钮,如何将图像加载到imageView

时间:2016-07-07 06:01:31

标签: android imageview radio-button

您好,我正在做一个学校项目,而且我正在进行性别分类。如果我选择男性,应该在我的Android应用程序中加载一个男性图标到imageView和Vice Versa。

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

1 个答案:

答案 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>

如果您在使用我的代码时遇到问题,请发表评论,我会帮助您。