android - 选择为 textView 和 editText 添加边框形状时,

标签 android xml android-layout shapes

我想为 TextViewEditText 创建边框形状,并在 view选中.

就像这张图片

example

最佳答案

您应该使用可绘制选择器来实现您的 UI。

首先创建一个background_edit_text_default.xml,它是EditText未被用户选中时的背景。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1dp"
        android:color="#333D46" />

    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
</shape>

然后创建一个background_edit_text_selected.xml作为用户选中EditText时的背景。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1dp"
        android:color="#EDB90E" />

    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
</shape>

接下来创建一个 background_edit_text.xml,它将用作 EditText 的背景。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/background_edit_text_default" android:state_focused="false" />
    <item android:drawable="@drawable/background_edit_text_selected" android:state_focused="true" />

</selector>

最后将 background_edit_text.xml 设置为布局文件中 EditText 的背景,例如 activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/conteiner"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background_edit_text" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background_edit_text" />

</LinearLayout>

您已完成,无需在代码中添加任何内容。

关于android - 选择为 textView 和 editText 添加边框形状时,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353887/

相关文章:

android - 详细和调试日志未显示在logcat中

java - 反序列化错误时使 Firestore 缓存无效

android - 在模块 guava-26.0-android.jar 中发现重复的类 com.google.common.util.concurrent.ListenableFuture

sql - 使用 SQL 解析 XML

jquery - MVC Razor 以 XML 形式提交数据

Android @RestService 通过 androidannotations 注入(inject)导致 nullPointerException

java - 使用 XSLT 删除具有空/无属性的空节点

android - 带有 viewpager 的协调器布局,滚动不起作用

Android ListView 分隔符奇怪的问题

Android EditText 没有聚焦