728x90

LinearLayout 에서 horizontal 로 검색어를 배치하는 방법이다.

<LinearLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent"
     android:orientation="horizontal" >
<EditText
     android:layout_height="wrap_content" 
     android:layout_weight="1"
     android:layout_width="0dp"/>
 <Button
    android:text="Button"
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/>
 </LinearLayout>

별로 깔끔한 디자인이 아니라서 Material Design 을 적용해서 테스트해 봤다.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <com.google.android.material.textfield.TextInputLayout
	style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
	android:layout_width="0dp"
	android:layout_height="wrap_content"
	android:layout_weight="1"
	app:shapeAppearance="@style/ShapeAppearance.MaterialComponents.MediumComponent"
	app:boxStrokeColor="@color/blue_500"
	app:endIconMode="clear_text"
	android:hint="검색어"
	android:layout_marginLeft="5dp"
	android:layout_marginRight="5dp">

	<com.google.android.material.textfield.TextInputEditText
	    android:id="@+id/list_search_edit"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.button.MaterialButton
	android:id="@+id/list_search_btn"
	style="@style/Widget.MaterialComponents.Button.OutlinedButton"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_gravity="center_vertical"
	android:layout_marginRight="5dp"
	app:strokeColor="@color/blue_700"
	app:strokeWidth="1dp"
	android:text="검색"
	android:textSize="18sp" />

</LinearLayout>

그러나 원하는 결과가 나오지 않았다.

 

android SearchView 기능을 이용하여 원하는 결과를 얻을 수 있다.

<androidx.appcompat.widget.SearchView
    android:id="@+id/list_search_edit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    app:iconifiedByDefault="false"
    app:queryHint="검색어를 입력하세요"/>

Java 소스코드 처리

import androidx.appcompat.widget.SearchView;

SearchView search_view;
private ArrayList<Group_Item> groupItemList = new ArrayList<>(); // 서버에서 가져온 원본 데이터 리스트

search_view = findViewById(R.id.list_search_edit);
search_view.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
	// do something on text submit
	searchData(query);
	return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
	if(newText.length() == 0){
	    groupItemList.clear();
	}
	return false;
    }
});

검색어를 입력할 때마다 데이터를 서버에서 가져오는 것은 원하는 결과가 아닌 거 같아서

검색어를 입력하고 나서 검색 아이콘을 눌렀을 때 서버로부터 결과를 가져오고,

검색어를 삭제하면 ArrayList 데이터를 초기화하는 로직을 사용했다.

블로그 이미지

Link2Me

,