Make an Android button change background on click through XML

后端 未结 5 1622
春和景丽
春和景丽 2020-11-27 02:59

Is there a way to specify an alternative background image/color for a Button in the XML file that is going to be applied onClick, or do I have to do a But

相关标签:
5条回答
  • 2020-11-27 03:28
    public void methodOnClick(View view){
    
    Button.setBackgroundResource(R.drawable.nameImage);
    
    }
    

    i recommend use button inside LinearLayout for adjust to size of Linear.

    0 讨论(0)
  • 2020-11-27 03:32

    Try:

    public void onclick(View v){
                ImageView activity= (ImageView) findViewById(R.id.imageview1);
            button1.setImageResource(R.drawable.buttonpressed);}
    
    0 讨论(0)
  • 2020-11-27 03:33

    To change image by using code

    public void onClick(View v) {
       if(v == ButtonName) {
         ButtonName.setImageResource(R.drawable.ImageName);
       }
    }
    

    Or, using an XML file:

    <?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:state_pressed="true"
       android:drawable="@drawable/login_selected" /> <!-- pressed -->
      <item android:state_focused="true"
       android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
      <item android:drawable="@drawable/login" /> <!-- default -->
    </selector>
    

    In OnClick, just add this code:

    ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));
    
    0 讨论(0)
  • 2020-11-27 03:43

    I used this to change the background for my button

                button.setBackground(getResources().getDrawable(R.drawable.primary_button));
    

    "button" is the variable holding my Button, and the image am setting in the background is primary_button

    0 讨论(0)
  • 2020-11-27 03:47

    In the latest version of the SDK, you would use the setBackgroundResource method.

    public void onClick(View v) {
       if(v == ButtonName) {
         ButtonName.setBackgroundResource(R.drawable.ImageResource);
       }
    }
    
    0 讨论(0)
提交回复
热议问题