Header ads

Header ads
» » SearchView

SearchView trong Android

SearchView hỗ trợ cho người dùng những gợi ý liên quan khi bạn nhập vào trường EditText. Những gợi ý đó sẽ được hiển thị trong một danh sách thả xuống từ đó người dùng có thể chọn một item để thay thế cho nội dung của mình vừa nhập vào.

SearchView code trong XML

  <SearchView  android:id="@+id/simpleSearchView"  android:layout_width="wrap_content"  android:layout_height="wrap_content" />

Các phương thường sử dụng của SearchView 
1. getQuery():
 Phương thức này được sử lấy kết quả câu tìm kiếm của người sử dụng nhập vào trong SearchView . Phương thức này trả về kiểu dữ liệu là CharSequence.
Ví dụ sau lấy chuỗi tim kiếm trong SearchView

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view  CharSequence query = simpleSearchView.getQuery(); // get the query string currently in the text field

2. getQueryHint(): Phương thức này được sử dụng lấy chuỗi hint trongSearchView . Phương thức này trả về kiểu dữ liệu là CharSequence.
Ví dụ sau lấy chuỗi hint trong SearchView

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view  CharSequence queryHint = simpleSearchView.getQueryHint(); // get the hint text that will be displayed in the query text field

3. isIconfiedByDefault(): Phương thức này kiểm tra trạng thái mặc định con trỏ nhập trước icon searh hay sau icon search của SearchView. Phương thức này trả về giá trị true hoặc false

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view  boolean isIconfied=simpleSearchView.isIconfiedByDefault(); // checks default iconified state of the search field

4. setIconifiedByDefault(Boolean iconify): Phương thức này được sử dụng để thiết lập icon search trước con trỏ nhập hay icon search sau con trỏ nhập. Nếu true icon search trước con trỏ nhập ngược lại. Tham số truyền vào là true hoặc false.

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view  simpleSearchView.setIconifiedByDefault(false);  // set the default or resting state of the search field

5. setQueryHint(CharSequence hint): Phương thức này được sử dụng để thiết lập chuỗi hint trong SearchView. 
Ví dụ sau thiết lập hint trong SearchView

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view  simpleSearchView.setQueryHint("Search View"); // set the hint text to display in the query text field

6. setOnQueryTextFocusChangeListener(OnFocusChangeListenerlistener): Sự kiện này được gọi khi Text thay đổi.

Ví dụ sau thiết lập sự kiện setOnQueryTextFocusChangeListener() trong SearchView.

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view    // perform set on query text focus change listener event  simpleSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {  @Override  public void onFocusChange(View v, boolean hasFocus) {  // do something when the focus of the query text field changes  }  });

7. setOnQueryTextListener(OnQueryTextListenerlistener): Interface này dùng để lắng nghe sự kiện QueryTextChange
Ví dụ sau thiết lập sự kiện setOnQueryTextListener cho SearchView.

  SearchView simpleSearchView = (SearchView) findViewById(R.id.simpleSearchView); // inititate a search view    // perform set on query text listener event  simpleSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {  @Override  public boolean onQueryTextSubmit(String query) {  // do something on text submit  return false;  }    @Override  public boolean onQueryTextChange(String newText) {  // do something when text changes  return false;  }  });

Thuộc tính thường dùng của SearchView

Bây giờ chúng xem một số thuộc tính hay sử dụng trong SearchViewtrong tập tin XML

1. android:id: Là thuộc tính duy nhất của SearchView.

  <!--  id of an search view used to uniquely identify it -->  <SearchView  android:id="@+id/simpleSearchView"  android:layout_width="wrap_content"  android:layout_height="wrap_content" />

Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:

  SearchView simpleSearchView  = (SearchView) findViewById(R.id.simpleSearchView);

2. android:queryHint: Thuộc tính queryHint để hiển thị thông tin gợi ý trong vùng nhập dữ liệu khi bạn chưa nhập bất kỳ dữ liệu nào vào, chỉ cần có dữ liệu là phần queryHint sẽ tự động mất đi.
Ví dụ sau thiết lập queryHint trong SearchView.

  <SearchView  android:id="@+id/simpleSearchView"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:iconifiedByDefault="false"  android:queryHint="Search Here" /><!-- set query string of an search view -->

3. android:iconifiedByDefault: Thuộc tính này dùng để thiết lập icon search trước con trỏ nhập hay icon search sau con trỏ nhập. Nếu true icon search trước con trỏ nhập ngược lại

Ví dụ sau chúng ta thiết lập thuộc tính này là true

   <SearchView          android:id="@+id/searchView1"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:iconifiedByDefault="true"          android:queryHint="Search view" >  </SearchView>

4. android:background: Thuộc tính này xác định màu nền cho SearchView
Ví dụ sau thiết lập màu nền là màu đỏ

5. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của SearchView với nội dung nó chứa: left, right, top or bottom. Cũng ví dụ trên bây giờ chúng ta xác định padding=40dp từ mọi phía của SearchView.

  <SearchView      android:id="@+id/simpleSearchView"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:iconifiedByDefault="false"      android:queryHint="Search View"      android:background="#f00"      android:padding="40dp"/> <!-- set 40 dp padding from all the sides of a search view -->


Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có 1 ListView và 1 SearchView. Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml  thiết kế giao diện sau:

Bước 1: Tạo một project tên là SearchViewFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng SearchView và ListView trong  Relative Layout.

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="fill_parent"      android:layout_height="fill_parent">        <SearchView          android:id="@+id/search"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:iconifiedByDefault="false">            <requestFocus />      </SearchView>        <ListView          android:id="@+id/listview"          android:layout_width="fill_parent"          android:layout_height="fill_parent"          android:layout_below="@+id/search" />    </RelativeLayout>

Bước 3: Tạo một tin Layout  res-> right click trên layout -> New -> Activity -> Blank Activity và tạo list_view_items

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:padding="10dp">            <TextView          android:id="@+id/nameLabel"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="Animal : " />        <TextView          android:id="@+id/name"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_toRightOf="@+id/nameLabel" />        </RelativeLayout>

Bước 4: Tạo một lớp mới. Mở app -> java -> right click lên package-> New -> Java Class và tạo  AnimalNames.java .

  package hiepsiit.com.searchview;    public class AnimalNames {      private String animalName;        public AnimalNames(String animalName) {          this.animalName = animalName;      }        public String getAnimalName() {          return this.animalName;      }    }  

Bước 5: Tạo một lớp mới.Mở app -> java -> right click lên package-> New -> Java Class và tạo ListViewAdapter.java

  package hiepsiit.com.searchview;    import android.content.Context;  import android.view.LayoutInflater;  import android.view.View;  import android.view.ViewGroup;  import android.widget.BaseAdapter;  import android.widget.TextView;  import java.util.ArrayList;  import java.util.List;  import java.util.Locale;    public class ListViewAdapter extends BaseAdapter {        // Declare Variables        Context mContext;      LayoutInflater inflater;      private List<AnimalNames> animalNamesList = null;      private ArrayList<AnimalNames> arraylist;        public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {          mContext = context;          this.animalNamesList = animalNamesList;          inflater = LayoutInflater.from(mContext);          this.arraylist = new ArrayList<AnimalNames>();          this.arraylist.addAll(animalNamesList);      }        public class ViewHolder {          TextView name;      }        @Override      public int getCount() {          return animalNamesList.size();      }        @Override      public AnimalNames getItem(int position) {          return animalNamesList.get(position);      }        @Override      public long getItemId(int position) {          return position;      }        public View getView(final int position, View view, ViewGroup parent) {          final ViewHolder holder;          if (view == null) {              holder = new ViewHolder();              view = inflater.inflate(R.layout.list_view_items, null);              // Locate the TextViews in listview_item.xml              holder.name = (TextView) view.findViewById(R.id.name);              view.setTag(holder);          } else {              holder = (ViewHolder) view.getTag();          }          // Set the results into TextViews          holder.name.setText(animalNamesList.get(position).getAnimalName());          return view;      }        // Filter Class      public void filter(String charText) {          charText = charText.toLowerCase(Locale.getDefault());          animalNamesList.clear();          if (charText.length() == 0) {              animalNamesList.addAll(arraylist);          } else {              for (AnimalNames wp : arraylist) {                  if (wp.getAnimalName().toLowerCase(Locale.getDefault()).contains(charText)) {                      animalNamesList.add(wp);                  }              }          }          notifyDataSetChanged();      }    }

Bước 6: Mở src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo ListView SearchView.  Tiếp theo, chúng ta tạo 1 mảng dữ liệu và kết nối ListView thông qua đối tượng ArrayAdapter. Cuối cùng là thiết lập sự kiện cho SearchView.OnQueryTextListener cho SearchView để lọc câu truy vấn.

  package hiepsiit.com.searchview;    import java.util.ArrayList;    import android.app.Activity;  import android.os.Bundle;  import android.view.Menu;  import android.view.MenuItem;  import android.widget.ListView;  import android.widget.SearchView;    public class MainActivity extends  Activity implements SearchView.OnQueryTextListener{  	ListView list;      ListViewAdapter adapter;      SearchView editsearch;      String[] animalNameList;      ArrayList<AnimalNames> arraylist = new ArrayList<AnimalNames>();  	@Override  	protected void onCreate(Bundle savedInstanceState) {  		super.onCreate(savedInstanceState);  		setContentView(R.layout.activity_main);  		// Generate sample data            animalNameList = new String[]{"Lion", "Tiger", "Dog",                  "Cat", "Tortoise", "Rat", "Elephant", "Fox",                  "Cow","Donkey","Monkey"};            // Locate the ListView in listview_main.xml          list = (ListView) findViewById(R.id.listview);            for (int i = 0; i < animalNameList.length; i++) {              AnimalNames animalNames = new AnimalNames(animalNameList[i]);              // Binds all strings into an array              arraylist.add(animalNames);          }            // Pass results to ListViewAdapter Class          adapter = new ListViewAdapter(this, arraylist);            // Binds the Adapter to the ListView          list.setAdapter(adapter);            // Locate the EditText in listview_main.xml          editsearch = (SearchView) findViewById(R.id.search);          editsearch.setOnQueryTextListener(this);      }        @Override      public boolean onQueryTextSubmit(String query) {            return false;      }        @Override      public boolean onQueryTextChange(String newText) {          String text = newText;          adapter.filter(text);          return false;      }    	  }  

 


Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng:


 



Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com

About Học viện đào tạo trực tuyến

Xinh chào bạn. Tôi là Đinh Anh Tuấn - Thạc sĩ CNTT. Email: dinhanhtuan68@gmail.com .
- Nhận đào tạo trực tuyến lập trình dành cho nhà quản lý, kế toán bằng Foxpro, Access 2010, Excel, Macro Excel, Macro Word, chứng chỉ MOS cao cấp, IC3, tiếng anh, phần mềm, phần cứng .
- Nhận thiết kế phần mềm quản lý, Web, Web ứng dụng, quản lý, bán hàng,... Nhận Thiết kế bài giảng điện tử, số hóa tài liệu...
HỌC VIỆN ĐÀO TẠO TRỰC TUYẾN:TẬN TÂM-CHẤT LƯỢNG.
«
Next
Bài đăng Mới hơn
»
Previous
Bài đăng Cũ hơn