Как программно установить drawableLeft на кнопку Android?

Я динамически создаю кнопки. Сначала я стилизовал их с помощью XML, и я пытаюсь взять XML ниже и сделать его программным.

<Button
    android:id="@+id/buttonIdDoesntMatter"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="buttonName"
    android:drawableLeft="@drawable/imageWillChange"
    android:onClick="listener"
    android:layout_width="fill_parent">
</Button>

это то, что у меня есть до сих пор. Я могу сделать все, но выигрышного.

linear = (LinearLayout) findViewById(R.id.LinearView);
Button button = new Button(this);
button.setText("Button");
button.setOnClickListener(listener);
button.setLayoutParams(
    new LayoutParams(
        android.view.ViewGroup.LayoutParams.FILL_PARENT,         
        android.view.ViewGroup.LayoutParams.WRAP_CONTENT
    )
);      

linear.addView(button);

9 ответов


можно использовать setCompoundDrawables метод для этого. Пример здесь. Я использовал это без использования setBounds и это сработало. Вы можете попробовать в любом случае.

обновление: копирование кода здесь, Если ссылка идет вниз

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
img.setBounds( 0, 0, 60, 60 );
txtVw.setCompoundDrawables( img, null, null, null );

или

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
txtVw.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);

или

txtVw.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley, 0, 0, 0);

просто вы можете попробовать это

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

для меня, это сработало:

button.setCompoundDrawablesWithIntrinsicBounds(com.example.project1.R.drawable.ic_launcher, 0, 0, 0);

myEdtiText.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley,0, 0, 0);

Я сделал так:

 // Left, top, right, bottom drawables.
            Drawable[] drawables = button.getCompoundDrawables();
            // get left drawable.
            Drawable leftCompoundDrawable = drawables[0];
            // get new drawable.
            Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);
            // set image size (don't change the size values)
            img.setBounds(leftCompoundDrawable.getBounds());
            // set new drawable
            button.setCompoundDrawables(img, null, null, null);

может быть полезно:

TextView location;
location=(TextView)view.findViewById(R.id.complain_location);
//in parameter (left,top,right,bottom) any where you wnat to put
location.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.arrow,0);

***** Котлин Версия *****

используйте ниже фрагмент, чтобы добавить drawable слева к кнопке:

val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)

.

важный момент в использовании Android вектор Drawable

когда вы используете Android вектор drawable и хотите иметь обратную совместимость для API ниже 21 добавьте следующие коды:

на уровне приложения build.gradle:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

в классе приложений:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }

}

как указывает @Jérémy Reynaud, как описано в этом ответ, самый безопасный способ установить левый drawable без изменения значений других drawables (сверху, справа и снизу), используя предыдущие значения из кнопки с setCompoundDrawablesWithIntrinsicbounds:

Drawable leftDrawable = getContext().getResources()
                          .getDrawable(R.drawable.yourdrawable);

// Or use ContextCompat
// Drawable leftDrawable = ContextCompat.getDrawable(getContext(),
//                                        R.drawable.yourdrawable);

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

таким образом, все ваши предыдущие drawable будут сохранены.


попробуйте это:

((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);