Android,如何动态更改按钮内的可绘制对象?

Android, how can I change a drawable within a button dynamically?

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

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 属性?

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

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

请阅读 docs 了解更多信息。

如果要以编程方式设置可绘制对象,则必须使用

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);