android按钮切换文本与imageButton

时间:2016-03-12 01:03:19

标签: android button

我的button1带有文字" ohio&#34 ;, button2带有文字"阿拉斯加"和带有箭头的ImageButton作为背景。我想在单击ImageButton时将文本Button1切换到Button2,反之亦然,我该如何实现?或者github中有任何我可以尝试的参考吗?

2 个答案:

答案 0 :(得分:1)

据我了解你将imageButton作为切换点击它时你在这里改变文字是代码

 boolean clicked = false;
String button1text = "ohio";
String button2text = "alaska";

ImageButton mImageButton= (ImageButton) findViewById(R.id.imageButtonID);
Button mImageButton= (Button) findViewById(R.id.ButtonID);
Button mImageButton2= (Button) findViewById(R.id.ButtonID2);

mImageButton.setOnClickListener(this);
mImageButton.setOnClickListener(this);
mImageButton2.setOnClickListener(this);

@Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.imageButtonID:
              if(clicked){
               clicked = false;
               mImageButton.setText(button1text);
               mImageButton2.setText(button2text );
               }else{
                mImageButton.setText(button2text);
                mImageButton2.setText(button1text );
                clicked = true;
                 }
             break;
              }
}

答案 1 :(得分:0)

您可以在XML中为button1设置ID,为button2设置其他ID 在您的活动中,您可以执行以下操作:

ImageButton imageButton = (ImageButton) findViewById(R.id.ID_IMAGE_BUTTON));
imageButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Button button1 = (Button) findById(R.id.ID_BUTTON1);
        String textButton1 = button1.getText().toString;

        Button button2 = (Button) findById(R.id.ID_BUTTON2);
        String textButton2 = button2.getText().toString;

        button1.setText(textButton2);
        button2.setText(textButton1);
    }
});