0

I am trying to have an text and image on a button appear dynamically - the text needs to appear on the left and the image to appear on the right. To give an example, here is an image I would like to get.

ExampleButton

After searching through a few other examples on StackOverflow, tried the following code in my activity but it doesnt seem to be working. Can anyone please suggest what I am doing wrong ?

Code :

btn.setTextColor(Color.parseColor("#000000"));
btn.setText("SomeText");
btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mediumTextSize);

Drawable icon= getApplicationContext().getResources().getDrawable( R.drawable.cal);
icon.setBounds(0, 0, 0, 0); //Left,Top,Right,Bottom
btn.setCompoundDrawablesWithIntrinsicBounds( null, null, icon, null );
9
  • Do you want to set image on button ? Commented Dec 29, 2018 at 18:41
  • I suggest to use ImageButton Commented Dec 29, 2018 at 18:42
  • Else you can create LinearLayout and apply style Commented Dec 29, 2018 at 18:44
  • How about leaving out the two lines before the last one and just using btn.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cal, 0); ? Commented Dec 29, 2018 at 18:48
  • 1
    The linked version of the method will take int values (resource identifiers) Commented Dec 29, 2018 at 19:08

2 Answers 2

2

I noticed that the size of the image is very important when using it on other objects - when I adjusted the image to a smaller size, my code worked fine....

The same code that I was trying earlier worked for me after resizing the image...

                    Button btn = new Button(this);
                    btn.setTextColor(Color.parseColor("#000000"));
                    btn.setText("SomeText");
                    btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mediumTextSize);
                    btn.setGravity(Gravity.CENTER | Gravity.LEFT);
                    Drawable icon= getApplicationContext().getResources().getDrawable(R.drawable.cal);
                    btn.setBackgroundResource(R.drawable.light_bg);
                    icon.setBounds(0, 0, 0, 0); //Left,Top,Right,Bottom
                    btn.setCompoundDrawablesWithIntrinsicBounds( null, null, icon, null);

Thank you all for your help and suggestions !

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

           btn.setText("Some Text");
            btn.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
            btn.setGravity(Gravity.CENTER | Gravity.LEFT);
            Drawable myDrawable = 
            getResources().getDrawable(R.drawable.ic_cancel_black_24dp);
            btn.setCompoundDrawablesWithIntrinsicBounds(null,null,myDrawable,null);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.