【问题标题】:Android, how can I change a drawable within a button dynamically?Android,如何动态更改按钮内的可绘制对象?
【发布时间】:2015-09-29 03:42:28
【问题描述】:

所以我有这种方法可以在每次单击按钮时更改按钮中的文本:

final Button button1 = (Button) rootView.findViewById(R.id.inputModeSelector);
    button1.setTag(1);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            final int status =(Integer) v.getTag();
            if(status == 1) {
                button1.setText("Pic");

                v.setTag(0); //pause
            } else {
                button1.setText("Text");
                v.setTag(1); //pause
            }

            Toast.makeText(getActivity().getBaseContext(), "Changed Input Type", Toast.LENGTH_SHORT).show();
        }
    });

在按钮的样式中我有:

android:drawableLeft="@drawable/ic_assignment_white_18dp"

这会放置一个图标来强调文本模式。我的问题是如何将该图标更改为其他图标以配合相机模式,或者基本上如何设置 drawableLeft 属性?

【问题讨论】:

  • 创建一个带有多个“级别”的Drawableandroid.graphics.drawable.LevelListDrawable 并相应地设置级别

标签: android button click drawable


【解决方案1】:

您可以使用setCompoundDrawablesWithIntrinsicBounds() 以编程方式设置drawableLeft,如下所示

button1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.yourdrawable, 0, 0, 0);

请阅读docs了解更多信息。

【讨论】:

    【解决方案2】:

    如果你想以编程方式设置drawable,你必须使用

    button.setCompoundDrawablesWithIntrinsicBounds(int leftDrawableId, int topDrawableId, int rightDrawableId, int bottomDrawableId);
    

    所以如果你想设置drawable left,只需将drawable的id赋给setCompoundDrawablesWithInstrinsicBounds()的对应参数,其余保持null或0即可。 例如:

    button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.textIcon, 0, 0, 0);
    

    类似的,如果你想设置正确的drawable必须这样做:

    button.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.textIcon, 0);
    

    【讨论】: