android开发分享以编程方式在TextView中设置左边的drawable

我有一个XML文本在这里。

<TextView android:id="@+id/bookTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:drawableLeft="@drawable/checkmark" android:gravity="center_vertical" android:textStyle="bold" android:textSize="24dip" android:maxLines="1" android:ellipsize="end"/> 

正如你所看到的,我将DrawableLeft设置为xml。

我想改变代码中的drawable。

有没有办法去做这件事? 或者在文本视图的代码中设置drawableLeft?

    你可以使用setCompoundDrawablesWithIntrinsicBounds(int left,int top,int right,int bottom)

    设置0,你不想要的图像

    左侧可绘制的示例:

     TextView textView = (TextView) findViewById(R.id.myTxtView); textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0); 

    提示:只要您知道任何XML属性,但不知道如何在运行时使用它。 只需转到开发人员文档中的该属性的描述。 在那里你会发现相关的方法,如果它在运行时支持。 即对于DrawableLeft

    从这里我看到方法setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)可以用来做到这一点。

    您可以使用以下任何方法在TextView上设置Drawable:

    1- setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)

    2- setCompoundDrawables(Left_Drawable,Top_Drawable,Right_Drawable,Bottom_Drawable)

    并且从资源中获取可以使用:

     getResources().getDrawable(R.drawable.your_drawable_id); 

     static private Drawable **scaleDrawable**(Drawable drawable, int width, int height) { int wi = drawable.getIntrinsicWidth(); int hi = drawable.getIntrinsicHeight(); int dimDiff = Math.abs(wi - width) - Math.abs(hi - height); float scale = (dimDiff > 0) ? width / (float)wi : height / (float)hi; Rect bounds = new Rect(0, 0, (int)(scale * wi), (int)(scale * hi)); drawable.setBounds(bounds); return drawable; } 

      以上就是android开发分享以编程方式在TextView中设置左边的drawable相关内容,想了解更多android开发(异常处理)及android游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/addevelopment/518216.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐