Calling setCompoundDrawables() doesn't display the Compound Drawable

后端 未结 10 984
自闭症患者
自闭症患者 2020-12-04 06:58

After I call the setCompoundDrawables method, the compound Drawable is not shown..

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn.setC         


        
相关标签:
10条回答
  • 2020-12-04 07:44

    For me setCompoundDrawablesWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable) did not work.

    I had to use setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0).

    0 讨论(0)
  • 2020-12-04 07:44

    Example with Kotlin:

        val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
        myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)
    
    0 讨论(0)
  • 2020-12-04 07:45

    Image is blank because it hasn't got specified bounds. You may use setCompoundDrawables() but before you should specify image's bounds, using Drawable.setBounds() method

    0 讨论(0)
  • 2020-12-04 07:46

    The Image is not shown as you didn't specify the bounds, so you have 2 options here.

    1st Method

    Use setCompoundDrawablesWithIntrinsicBounds method, as shown below

    Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
    btn. setCompoundDrawablesWithIntrinsicBounds(myDrawable, null, null, null);
    

    2nd Method

    You can apply bounds to the drawable before applying to the TextView, as shown below

    Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
    myDrawable.setBounds( 0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
    btn.setCompoundDrawables(myDrawable, null, null, null);
    

    That's it.

    0 讨论(0)
  • 2020-12-04 07:50

    Example set to the top:

    view.setCompoundDrawablesWithIntrinsicBounds(
        null,
        getResources().getDrawable(R.drawable.some_img),
        null,
        null
    );
    

    arguments order: (left, top, right, bottom)

    0 讨论(0)
  • 2020-12-04 07:51

    A little bit simpler again:

    Drawable image = context.getResources().getDrawable(R.drawable.ic_action );
    image.setBounds( 0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight() );
    button.setCompoundDrawables( image, null, null, null );
    
    0 讨论(0)
提交回复
热议问题