Как программно установить 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);
Ответы
Ответ 1
Для этого вы можете использовать метод setCompoundDrawables
. См. Пример здесь. Я использовал это без использования setBounds
, и он сработал. Вы можете попробовать в любом случае.
UPDATE. Копирование кода здесь приведет к снижению ссылки.
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);
Ответ 2
Просто вы можете попробовать это и
txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
Ответ 3
Для меня это сработало:
button.setCompoundDrawablesWithIntrinsicBounds(com.example.project1.R.drawable.ic_launcher, 0, 0, 0);
Ответ 4
myEdtiText.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley,0, 0, 0);
Ответ 5
Я сделал это:
// 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);
Ответ 6
• Kotlin Version
Используйте фрагмент ниже, чтобы добавить левую кнопку для кнопки:
val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
,
• Important Point in Using Android Vector Drawable
Если вы используете векторное изображение для Android и хотите иметь обратную совместимость для API ниже 21, добавьте следующие коды:
На уровне приложения build.gradle
:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
В классе приложений:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
}
Ответ 7
как @Jérémy Reynaud, указывая, как описано в этом answer, самый безопасный способ установить левую растяжку без изменения значений других чертежей (сверху, вправо, и внизу), используя предыдущие значения с помощью кнопки 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]);
Таким образом, все ваши предыдущие доступные файлы будут сохранены.
Ответ 8
Ниже приведен способ изменить цвет левого значка в редактируемом тексте и установить его в левой части.
Drawable img = getResources().getDrawable( R.drawable.user );
img.setBounds( 0, 0, 60, 60 );
mNameEditText.setCompoundDrawables(img,null, null, null);
int color = ContextCompat.getColor(this, R.color.blackColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
DrawableCompat.setTint(img, color);
} else {
img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Ответ 9
Может быть полезно:
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);
Ответ 10
Попробуй это:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
fillButton[i].setBackground(getBaseContext().getResources().getDrawable(R.drawable.drawable_name));
}
else{
fillButton[i].setBackgroundColor(Color.argb(255,193,234,203));
}
Ответ 11
Если вы используете drawableStart, drawableEnd, drawableTop или drawableBottom; Вы должны использовать " setCompoundDrawablesRelativeWithIntrinsicBounds "
edittext.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.anim_search_to_close, 0)
Ответ 12
String countryIso = objPrefs.getAddBusinessFlagCode();
countryIso = countryIso.toLowerCase();
add_business_country.setCompoundDrawablesWithIntrinsicBounds(getApplicationContext().getResources().getIdentifier("drawable/" + countryIso, null, getApplicationContext().getPackageName()), 0, 0, 0);
Ответ 13
Попробуй это:
((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);