【问题标题】:Programmatically change drawableLeft of Button以编程方式更改按钮的drawableLeft
【发布时间】:2013-08-16 16:27:42
【问题描述】:

我正在使用按钮

<Button
        android:id="@+id/zoom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/trans"
        android:drawableLeft="@drawable/left_img"
        android:fontFamily="arial"
        android:text="My Name is "
        android:textSize="50sp" />

并使用 :

更改其文本颜色
zoom.setTextColor(Color.parseColor("voilet"));

但看不懂how to change its image??

【问题讨论】:

标签: android image button textview drawable


【解决方案1】:

试试这个:

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

Reference

【讨论】:

    【解决方案2】:

    在不更改其他可绘制对象(顶部、右侧和底部)的值的情况下设置左侧可绘制对象的最安全方法:

    Drawable[] drawables = textViewExample.getCompoundDrawables();
    textViewExample.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, drawables[1], drawables[2], drawables[3]);
    

    【讨论】:

      【解决方案3】:

      为此,您可以使用

      setCompoundDrawables(...);

      方法。请注意 TextView 附带,而不是 Button。

      这是如何使用它:

      Drawable img = getContext().getResources().getDrawable( R.drawable.yourimage);
      img.setBounds( 0, 0, 60, 60 );  // set the image size
      txtVw.setCompoundDrawables( img, null, null, null );
      

      取自:How to programmatically set drawableLeft on Android button?

      【讨论】:

      • 如何在文本视图的右侧设置图像
      【解决方案4】:

      我建议您不要使用按钮,而是使用 Imageview 并向其添加 onclick 侦听器。这样你就可以做Imageview.setbitmap(bitmap) 并从你的一个drawables中创建一个位图

      【讨论】:

        【解决方案5】:

        只要按照这个代码,我希望它真的对你有帮助..

        boolean isIconChange;
        button.setOnClickListener(new OnClickListener() {
        
            @Override
            public void onClick(View arg0) {
                isIconChange = !isIconChange;
                if(isIconChange){
                   button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like, 0, 0, 0);
                   button.setTextColor(Color.BLACK);
                } else {
                   button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.dislike, 0, 0, 0);
                   button.setTextColor(Color.RED);
                }
            }
        });
        

        【讨论】:

          猜你喜欢
          • 2011-05-29
          • 1970-01-01
          • 2010-12-21
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多