javaandroidsearchactivity

What is R.layout.search?


I'm creating a search widget and a searchable activity. I followed the android developer guide and have this so far.

Here is my searchableActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    // Get the intent, verify the action and get the query
    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {

        String query = intent.getStringExtra(SearchManager.QUERY);
        doMySearch(query);
    }
}

As mentioned, R.layout.search is creating the error. I don't have a search xml in layouts, and I don't understand what I am supposed to define within search.xml.


Solution

  • You need to have a layout named search.xml in your res/layout folder where you'll show the search results. I my case I showed the search results in a RecyclerView and here's a sample layout of mine.

    <FrameLayout 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:background="@color/color_background_search">
    
        <LinearLayout
            android:id="@+id/empty_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:gravity="center_horizontal"
            android:orientation="vertical">
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:tint="@color/color_primary_light"
                android:src="@drawable/ic_action_search" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/empty_search_result"
                android:textColor="@color/black"
                android:textSize="20sp" />
        </LinearLayout>
    
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/search_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </FrameLayout>