【问题标题】:Make image and text appear side by side within button?使图像和文本在按钮内并排显示?
【发布时间】:2014-05-04 05:05:18
【问题描述】:

我想要一个按钮,里面有一个小图标和文本,图标位于按钮的左侧,如何将它移近居中的文本?

这是我的按钮 XML:

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/home_icon"
        android:text="BACK"
        android:id="@+id/button"
        android:width="160dp"
        android:height="70dp"
        android:textStyle="bold" />

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:
    <Button
     android:id="@+id/button1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:drawableLeft="@android:drawable/btn_star_big_on"
     android:text="Drawable left"/>
    

    【讨论】:

      【解决方案2】:

      不幸的是,不能使用drawableLeft 属性。此属性将图像定位到最左边的位置(无论您的文本在哪里)。

      您需要为此创建自己的按钮:

      <LinearLayout
          android:id="@+id/button"
          style="?android:attr/buttonStyle"
          android:layout_width="160dip"
          android:layout_height="70dip"
          android:gravity="center"
          android:orientation="horizontal" >
      
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/home_icon" />
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="BACK"
              android:textColor="@android:color/black" />
      </LinearLayout>
      

      【讨论】:

        【解决方案3】:

        你不能把它移近。如果您想让它们靠得更近,您唯一的选择是构建自己的按钮:

        <RelativeLayout
                  android:id="@+id/rlButton"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        
            <TextView
                    android:id="@+id/tvText"
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content"
                    android:text="@string/button_text"/>
        
            <ImageView
                    android:id="@+id/ivLeft"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/home_icon"
                    android:layout_toLeftOf="@id/tvText"/>
        
        </RelativeLayout>
        

        您可以使用边距来控制TextViewImageView 之间的距离。您可以像使用按钮一样使用它:

        RelativeLayour rlButton = (RelativeLayout) view.findViewById(R.id.rlButton);
        rlButton.setOnClickListener(new OnClickListener() {
            ....
        });
        

        当然,您必须将按钮样式应用到 RelativeLayout,使其看起来与按钮相同。

        【讨论】:

          猜你喜欢
          • 2019-03-10
          • 2020-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多