将形状添加到LinearLayout Android

Kha*_*dal 8 xml layout android shape android-layout

我有一个linearLayout有一些自动完成和文本框.我想在linearlayout中插入一个形状(矩形).我怎样才能做到这一点.我是android的新手.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"    
    android:padding="5dp"
    android:id="@+id/layout">

    <AutoCompleteTextView android:id="@+id/autocompleteCountry"
      android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/CONTRY_LABEL"
       />
    <AutoCompleteTextView android:id="@+id/locationAutoCompleteFrom"
      android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/from"
        android:visibility="gone"
       />
   <AutoCompleteTextView android:id="@+id/locationAutoCompleteTO"
      android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/to"
        android:visibility="gone"
       />
 <!--    <Button android:id="@+id/buttonRoute"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/buttonRouteText"
       android:enabled="false"
       android:clickable="true"
       />
   -->
Run Code Online (Sandbox Code Playgroud)

Boo*_*ger 14

您应该使用ShapeDrawable作为要添加样式的组件的背景.

可绘制的形状是用XML创建的,具有以下语法(这个显示一个带圆角的矩形,但是你可以做很多事情来自定义它以便你想要它).此文件(名为background_square.xml或其他)应放在drawable文件夹中:

 <?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <solid
        android:color="@color/primary_grey" /> 
</shape>
Run Code Online (Sandbox Code Playgroud)

然后,当您要将其添加到View时,可以在XML中使用以下语法:

android:background="@drawable/background_square"
Run Code Online (Sandbox Code Playgroud)

  • 我使用这个形状作为ImageView的来源,但否则很好!谢谢! (2认同)