Image button changes image

别来无恙 提交于 2019-12-25 00:34:31

问题


I have a image button and i want that image button when pressed it changes the text in a textbox and it changes a image to a different image how do i do this?


回答1:


You need an OnClickListener: http://developer.android.com/reference/android/view/View.OnClickListener.html

When clicked your text can be changed with (something like) text.setText("new text");

I'll find a link in a minute which will help more.




回答2:


This page shows you how to change the image onclick:

Make an Android button change background on click through XML




回答3:


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class TestesetetActivity extends Activity {
    /** Called when the activity is first created. */
    TextView textview = null;
    ImageButton buttonResume = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        buttonResume = (ImageButton) findViewById(R.id.imageButton1);
        textview = (TextView) findViewById(R.id.textView1);

        buttonResume.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                textview.setText("test");
                buttonResume.setImageResource(R.drawable.push_pin);
            }
        });
    }
}



回答4:


In the xml file, you can give the image an onClick attribute, which calls a method in the java class, which calls the xml resource, and passes it the id of the ImageView.

In that java method, you can use

((ImageView) view).setImageResource(int id)

or

setImageDrawable(Drawable d)

to change the image.

Likewise, you can identify the TextView you wish to change using, for example,

TextView tv = (TextView) findViewById( id )

with id being the id of the TextView you wish to find.

You can then use

tv.setText(String s)

to set the text in this view.




回答5:


In your OnClickListener, you could use

button.setBackgroundResource(YOUR_BUTTON_ID);

or

button.setImageResource(YOUR_BUTTON_ID);


来源:https://stackoverflow.com/questions/6779249/image-button-changes-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!