Android Imagebutton change Image OnClick

前端 未结 7 1109
心在旅途
心在旅途 2020-12-09 07:43

I just added a new drawable folder under res folder. In the drawable folder, i copied the ic_launcher.png file from

相关标签:
7条回答
  • 2020-12-09 08:10

    This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

    The following works fine :

    ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
     btn.setImageResource(R.drawable.actions_record);
    

    while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

    Thanks.

    0 讨论(0)
  • 2020-12-09 08:11

    You can do it right in your XML file:

    android:onClick="@drawable/ic_action_search"
    
    0 讨论(0)
  • 2020-12-09 08:15
    <ImageButton android:src="@drawable/image_btn_src" ... />
    

    image_btn_src.xml

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/icon_pressed"/>
    <item android:state_pressed="false" android:drawable="@drawable/icon_unpressed"/>
    </selector>
    
    0 讨论(0)
  • 2020-12-09 08:25

    You have assing button to your imgButton variable:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        imgButton = (Button) findViewById(R.id.imgButton);
        imgButton.setOnClickListener(imgButtonHandler);
    }
    
    0 讨论(0)
  • 2020-12-09 08:25

    It is very simple

    public void onClick(View v) {
    
            imgButton.setImageResource(R.drawable.ic_launcher);
    
        }
    

    Using set Background image resource will chanage the background of the button

    0 讨论(0)
  • 2020-12-09 08:28

    That is because imgButton is null. Try this instead:

    findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);
    

    or much easier to read:

    imgButton = (Button) findViewById(R.id.imgButton);
    imgButton.setOnClickListener(imgButtonHandler);
    

    then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);

    0 讨论(0)
提交回复
热议问题