将drawable添加到EditText的左上角

bla*_*lay 6 android drawable android-edittext

我知道在Android中我们可以使用函数setCompoundDrawables(..)来添加drawable.

我的问题是我的EditText是多行的,我想把drawable放在EditText的左上角.但是在setCompoundDrawables()函数中使用,只能选择将drawable放在特定的一面.

Android API是否有可能做到这一点?

san*_*tar 5

似乎不可能仅使用EditText/ TextView不使用anyside效果和其他视图(我已经提供了最终的方式,但是它需要更多的图像工作,并且可能不适用于每部手机,因为不同的编辑文本背光源取决于manufature).已经多次询问过同样的问题:例如这里这里.

根据我的理解,最容易和最紧固的方式可能不是上面提到的问题(通过使用RelativeLayout),但只是使用FrameLayout以下方式(你将有2个视图vs 3视图使用RelativeLayout+ ImageView):使你的图标9patch(使用9patch工具)).例如,您最初有以下图标:

原始图标

然后您可以将其转换为以下一个:

在此输入图像描述 (您可以看到黑色像素,显示要用视图拉伸的区域和内容区域)

使用以下xml:

    <!-- Main activity layout -->
    <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <!-- Edit text with drawable at top left -->
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@drawable/icon_9patch">
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/edit"
                android:hint="Enter text"
                android:maxLines="10"
                android:inputType="textMultiLine" />
        </FrameLayout>
    </RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

给出以下结果(我添加了多行文本):

结果图像

此外,甚至可以仅使用EditText(但你可能会松开默认的EditText背景,这可能不太好,但是你可以将它包含在你的ning-patch图像中;但它在所有手机上仍然是相同的而不是原生的一).

以下xml也可以正常工作:

<!-- Main activity layout -->
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Edit text with drawable at top left -->
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edit"
            android:hint="Enter text"
            android:maxLines="10"
            android:inputType="textMultiLine"
            android:layout_alignParentBottom="true"
            android:background="@drawable/icon_9patch" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

给出以下结果(请注意,编辑的默认框架已消失): 单视图外观