Sudeepta
Sudeepta

Reputation: 2204

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);

Upvotes: 3

Views: 1615

Answers (1)

Imran Rana
Imran Rana

Reputation: 11899

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)); 
    }

Upvotes: 1

Related Questions