在android中的Edit文本旁边绘制一个图像

时间:2012-01-19 10:09:37

标签: android android-layout

我想在EditText的左侧绘制一个图像。我不希望图像出现在EditText中。

我用这个:

<EditText
    android:id="@+id/firstNameTxt"
    style="@style/UserInfoInputs"
    android:drawablePadding="20dp"
    android:drawableLeft="@drawable/first_name" >
</EditText>

它显示EditText内部的图像。但是我在TextView上使用它并且它工作正常:

<TextView
    android:id="@+id/positionValue"
    style="@style/userInfo"
    android:drawableLeft="@drawable/position" />

如何为EditText做这件事?

3 个答案:

答案 0 :(得分:2)

试试这个

<LinearLayout 
        android:orientation="horizontal"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content">

          <ImageView
        android:id="@+id/go_image"
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"     
        android:src="@drawable/icon"
        />
        <EditText  
        android:id="@+id/url" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"     
        android:lines="1"
        android:layout_weight="1.0" />



    </LinearLayout>

让我知道这是否有效。

答案 1 :(得分:1)

您描述的两个用例之间的区别很简单。没有区别。使用EditText,有一些容易辨别的行。使用TextView没有。尝试设置textview的background属性,你会看到drawable实际上是在左侧绘制的,但仍然在'inside'中,TextView。

完成任务的最简单方法(如上所述)是使用ImageView。根据您使用的ViewGroup(LinearLayout,RelativeLayout等),代码可能会有所不同;所以,用适当的信息更新你的问题,我会更具体地说明我的答案。

我应该注意,您可以使用的另一种方法是创建自己的自定义组件,这非常容易。请参阅此文章Custom Components | Android Developer,确保向下滚动到“化合物控制”标题标题“化合物控制”。当这是您经常使用的“常见”控件格式时,这将特别有用(例如,您在应用程序中的TextView旁边有一个图像)。

答案 2 :(得分:0)

这是因为EditText的背景部分延伸到视图的整个内容后面,包括drawables 。 如果您使用RelativeLayout,则可以添加单独的ImageView

<ImageView
    layout_width="wrap_content"
    layout_height="wrap_content"
    layout_toLeftOf="@+id/firstNameTxt"
    src="@drawable/first_name"
    other imageview attributes as neccessary...
    />
<EditText
    android:id="@+id/firstNameTxt"
    style="@style/UserInfoInputs"
    />

或者,如果您使用其他类型的布局,请创建一个LinearLayout - 包装器:

<LinearLayout
    layout_width="wrap_content"
    layout_height="wrap_content">
    <ImageView
        layout_width="wrap_content"
        layout_height="wrap_content"
        layout_toLeftOf="@+id/firstNameTxt"
        src="@drawable/first_name"
        other imageview attributes as neccessary...
        />
    <EditText
        android:id="@+id/firstNameTxt"
        style="@style/UserInfoInputs"
        />
</LinearLayout>
相关问题