单击按钮显示图像

时间:2018-02-11 13:46:11

标签: java android image button

我正在尝试创建一个简单的Android应用程序,它有多个按钮但只有1个imageView。每个按钮都有一个独特的图像。单击时,它将显示在imageView中。这是我的java代码:

public void poundedYamFunction(View view){

    ImageView swallowImage = (ImageView) view;
    swallowImage.setImageResource(R.drawable.poundedyam);
}

public void ebaFunction(View view){

    ImageView swallowImage = (ImageView) view;
    swallowImage.setImageResource(R.drawable.eba);
}

public void semoFunction(View view){

    ImageView swallowImage = (ImageView) view;
    swallowImage.setImageResource(R.drawable.semo);
}

2 个答案:

答案 0 :(得分:1)

根据详细信息和代码,多个按钮与不同的视图相关联,此处的View view引用是Buttons而非imageview的引用,因此您需要初始化imageView参考并相应地设置图像。

ImageView img;

...oncreate(..){
    setContentView(..);
    img = (ImageView)findViewById(R.id.id_of_image_view);
}

public void poundedYamFunction(View view){

    img.setImageResource(R.drawable.poundedyam);
}

public void ebaFunction(View view){

    img.setImageResource(R.drawable.eba);
}

答案 1 :(得分:1)

您可以使用以下代码实现它。使用View.OnClickListeneronClick(View view)更改图片实施活动。

    public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {

    ImageView imageView;
    Button button1, button2;

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

        imageView = findViewById(R.id.image_view);
        button1 = findViewById(R.id.button_1);
        button2 = findViewById(R.id.button_2);

        imageView.setOnClickListener(this);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.button_1:
                imageView.setImageResource(R.drawable.poundedyam);
                break;

            case R.id.button_2:
                imageView.setImageResource(R.drawable.eba);
                break;
        }
    }
}