按钮和左侧可绘制

edi*_*233 7 android android-layout

我在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"
        />
Run Code Online (Sandbox Code Playgroud)

我想知道如何在活动中做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));
Run Code Online (Sandbox Code Playgroud)

Dhr*_*tel 20

Drawable image = getContext().getResources().getDrawable( R.drawable.icon );
image.setBounds( 0, 0, 60, 60 );
button.setCompoundDrawables( image, null, null, null );
Run Code Online (Sandbox Code Playgroud)

做这个

更新:

由于getContext().getResources().getDrawable现已弃用,请改用:

  Drawable image = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
  image.setBounds( 0, 0, 60, 60 );
  button.setCompoundDrawables( image, null, null, null );
Run Code Online (Sandbox Code Playgroud)


use*_*305 5

试试这个,

Drawable icon= getContext().getResources().getDrawable(R.drawable.icon);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
Run Code Online (Sandbox Code Playgroud)