7

次のようなxmlファイルにボタンを作成します。

    <Button
        android:id="@+id/call_button"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="30dp"
        android:background="@drawable/button"
        android:layout_weight="40" 
        android:drawableLeft="@drawable/symbol_phone"
        android:paddingLeft="20dp"
        android:drawablePadding="-25dp"
        android:text="Call"
        android:textColor="@color/white"
        />

アクティビティで drawableLeft を実行する方法を知りたいです。ばかげていることはわかっていますが、ボタンを作成するため、アクティビティでこれを行う必要があります。アクティビティでxmlファイルにあるものと同じことを行うにはどうすればよいですか? drawableLeft と drawable padding と padding left を追加する必要があります。これは、アクティビティでボタンを作成する方法です

 Button button1 = new Button(this);
 button1.setLayoutParams(new RelativeLayout.LayoutParams(buttonWidth, buttonHeight));
 button1.setText(systemTexts.getShowCallButton());
 button1.setBackgroundDrawable(new                                      
 button1.setTextColor(Color.parseColor(buttonTextColor));
4

5 に答える 5

20
Drawable image = getContext().getResources().getDrawable( R.drawable.icon );
image.setBounds( 0, 0, 60, 60 );
button.setCompoundDrawables( image, null, null, null );

これを行う

アップデート:

getContext().getResources().getDrawable現在は非推奨になっているため、代わりにこれを使用してください。

  Drawable image = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
  image.setBounds( 0, 0, 60, 60 );
  button.setCompoundDrawables( image, null, null, null );
于 2012-05-14T09:14:25.663 に答える
5

これを試して、

Drawable icon= getContext().getResources().getDrawable(R.drawable.icon);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
于 2012-05-14T09:15:15.460 に答える
2

プログラムでdrawableLeftを設定する方法は、setCompoundDrawablesWithIntrinsicBoundsを使用することです。

setPaddingでパディングを設定できます

ドキュメントには、すべてのxmlタグに対応するjavaメソッドが示されています。

于 2012-05-14T09:13:37.110 に答える