简体   繁体   中英

Android button with transperent png image and background colour

I need a button with foreground transparent image and background color. So have use this code. The background color is going outside of the image. I need the button with the same size of the image.

Depending on the user interaction i have to change the foreground image and background color. I want add the image and background color separately so that i can change one of them at minimum cost. I have to use a lot of button in this UI so it will be done in java code.

layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(8,7));
TableRow row2 = new TableRow(this);
buttonPlayer1 = new ImageButton(this);
buttonPlayer1.setImageDrawable(getResources().getDrawable(R.drawable.blankc4));
buttonPlayer1.setBackgroundColor(Color.GREEN);
row2.addView(buttonPlayer1);
layout.addView(row2);

If your only problem is that button background color is going outsize image and you need button size to be same as image size then get image Height and Width using getHeight() & getWidth() methods on image object and use these values to make the Button size same as Image size using setHeight() & setWidth() methods respectively on button object.

Sample Code with LinearLayout:


 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout btnLO = new LinearLayout(this);    
        btnLO.setOrientation(LinearLayout.VERTICAL);
        ImageButton i1 = new ImageButton(this);
        i1.setBackgroundColor(color.background_dark);
        i1.setImageDrawable(getResources().getDrawable(R.drawable.rana));   
        btnLO.addView(i1, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));                      
  //    btnLO.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL);     
        this.addContentView(btnLO, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM