
Mặc dù Android có sẵn chức năng SearchView trên ActionBar, nhưng với máu nhà nghề của một Web Designer, tôi vẫn muốn làm riêng cho mình một cái SearchBar thật dễ thương. Và đây là code cho file activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" android:padding="10dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="@drawable/botron_edittext" android:layout_gravity="top" android:paddingLeft="3dp" android:paddingRight="5dp" android:paddingTop="0dp" android:paddingBottom="0dp"> <EditText android:id="@+id/edtSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/botron_edittext" android:singleLine="true" android:hint="Tìm Bài hát/Nhạc sĩ"/> <Button android:id="@+id/btnSearch" android:layout_width="25dp" android:layout_height="25dp" android:layout_marginLeft="5dp" android:layout_marginTop="-2dp" android:background="@drawable/icon_search"/> </LinearLayout> </LinearLayout> ...
Trong drawable, ta tạo file botron_edittext.xml như sau:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<!-- Set màu nền-->
<solid android:color="#ffffff"></solid>
<!-- đặt thuộc tính màu và độ rộng của đường viền -->
<stroke android:width="1dp" android:color="#ffffff" ></stroke>
<!-- các thuộc tính căn chỉnh-->
<padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" ></padding>
<!-- và đây là bán kính đường tròn ở 4 góc -->
<corners android:radius="2dp" >
</corners>
</shape>
Và một file icon_search.png:

Xong rồi đó, đẹp lộng lẩy!
