Android ボタンにプログラムで drawableLeft を設定するにはどうすればいいですか? 質問する

Android ボタンにプログラムで drawableLeft を設定するにはどうすればいいですか? 質問する

動的にボタンを作成しています。最初に 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>

今のところはこんな感じです。drawable 以外はすべてできます。

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、うまくいきました。どちらの方法でも試すことができます。

更新: リンクが切れた場合に備えて、ここにコードをコピーします

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

おすすめ記事