【问题标题】:How to assign an image to a button?如何将图像分配给按钮?
【发布时间】:2010-07-08 12:45:30
【问题描述】:

我想为我的活动中的某个按钮分配一张图片?

我怎样才能做到这一点? 为此,我应该将 image.jpeg 或任何其他图像文件放在哪里?

【问题讨论】:

    标签: android image button


    【解决方案1】:

    使用ImageButton。 将您的图像放入资源中,并像这样使用它:

     <?xml version="1.0" encoding="utf-8"?>
     <selector xmlns:android="http://schemas.android.com/apk/res/android">
         <item android:state_pressed="true"
               android:drawable="@drawable/button_pressed" /> <!-- pressed -->
         <item android:state_focused="true"
               android:drawable="@drawable/button_focused" /> <!-- focused -->
         <item android:drawable="@drawable/button_normal" /> <!-- default -->
     </selector>
    

    【讨论】:

      【解决方案2】:

      这是一个很老的问题,但您似乎没有在这篇文章中得到最佳解决方案,因为仍然没有接受任何答案。

      So if we need a "button with Image" then we have two options
      
      1. 我们可以选择图像按钮作为他的回答中提到的“Orsol”

      2. 或者您可以简单地添加普通按钮,然后使用属性将图像设置为背景

      代码会是这样的

      <Button 
      android:background="@drawable/square_1_up" 
      android:layout_height="62dp" 
      android:layout_width="65dp" 
      android:id="@+id/button1">
      </Button>
      

      为此,我们需要将按钮图像放在名为“square_1_up.png”的 Drawable 文件夹中

      输出按钮会像

      【讨论】:

        【解决方案3】:

        将这些文件保存在 res/drawable/button.xml 下

        <?xml version="1.0" encoding="utf-8"?>
        <selector xmlns:android="http://schemas.android.com/apk/res/android">
         <item android:state_pressed="true"
               android:drawable="@drawable/button_pressed" /> <!-- pressed -->
         <item android:state_focused="true"
               android:drawable="@drawable/button_focused" /> <!-- focused -->
         <item android:drawable="@drawable/button_normal" /> <!-- default -->
        </selector>
        

        假设你的主布局文件 main.xml 在 res/layout/main.xml 下

        <LinearLayout>
         <ImageButton
         android:src="@drawable/button.xml"
         android:layout_width="fill_parent"
         android:layout_heght="wrap_content"
         android:id="@+id/button1"  
         />
        </LinearLayout>
        

        【讨论】:

          猜你喜欢
          • 2014-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-07
          相关资源
          最近更新 更多