按钮和可绘制左侧图标

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"
        />

我想知道如何在Activity中实现drawableLeft。我知道这很愚蠢,但是我需要在Activity中创建按钮,所以需要这样做。我该如何在Activity中实现与XML文件相同的效果?我需要添加drawableLeft、drawable padding和padding left。

以下是我在Activity中创建按钮的方式:

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

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

5
试试这个,
Drawable icon= getContext().getResources().getDrawable(R.drawable.icon);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);

2

0
你可以尝试这个:
txtVw.setCompoundDrawables(R.drawable.img_nature, 0, 0, 0);

-1

您可以使用以下代码

<Button android:text="@string/button_label" 
android:id="@+id/buttonId"
android:layout_width="160dip"
android:layout_height="60dip"
android:layout_gravity="center"
android:textSize="13dip"
android:drawableLeft="@drawable/button_icon"
android:drawablePadding="2dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:singleLine="true"
android:gravity="center" />  

它将通过对文本和图像进行填充来管理


我觉得你没有回答这个问题,OP想要通过编程来实现它。 - Joffrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接