繁体   English   中英

以列表项为结果的 Android SearchView 小部件

[英]Android SearchView Widget With List Item as a Result

任何人都可以给我一个关于如何使用searchView widget(not in action bar)根据用户在 searchView 中键入的内容来显示结果列表的解决方案。
我在开发 android 应用程序方面很新,碰巧我想尝试创建一个可以从数据库中检索数据的简单应用程序。
我尝试从互联网上进行搜索,我找到了可以搜索数据的'searchView'
我从互联网上复制了代码并修改了某些部分。 我阅读了代码,我实际上理解了一些代码但不是全部,现在从MainActivity ,我看到了'onSearchRequested();' 被调用,然后意图searchView in action barsearchView in action bar开始。
我尝试通过在布局中放置一个 searchView 小部件来修改代码,我想使用它而不是'onSearchRequested();' 但我有货,不知道如何显示'ListView'作为结果。

这就是运行的样子:
操作栏中的搜索视图
在此处输入图片说明

我想改变它:
带有列表项结果但不在操作栏中的 searchView
在此处输入图片说明

编码::

'MainActivity.java' // 原来的

public class MainActivity extends FragmentActivity{

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.btn_search);    
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {           
                onSearchRequested();    // This will start eveything on button click            
            }
        });
    }
}

'MainActivity.java' // 我已经修改了

public class MainActivity extends FragmentActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.btn_search);    
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {           
                onSearchRequested();                
            }
        });


        SearchView searchView = (SearchView)findViewById(R.id.searchView1);

        //This is just some code trying to customize the SearchView 
        searchView.setQueryHint("Type Word...");
        int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
        View searchPlate = searchView.findViewById(searchPlateId);
        if (searchPlate!=null) {
            searchPlate.setBackgroundColor(Color.WHITE);
            int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
            TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
            if (searchText!=null) {
                searchText.setTextColor(Color.DKGRAY);
                searchText.setHintTextColor(Color.LTGRAY);

            }
        }

        // and im stock here, dont now what next to do

    }
}

SearchableActivity.java //这里什么都没有修改

public class SearchableActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {

    ListView mLVCountries;
    SimpleCursorAdapter mCursorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchable);
        // Getting reference to Country List
        mLVCountries = (ListView)findViewById(R.id.lv_countries);       
        // Setting item click listener      
        mLVCountries.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent countryIntent = new Intent(getApplicationContext(), CountryActivity.class);
                // Creating a uri to fetch country details corresponding to selected listview item
                Uri data = Uri.withAppendedPath(CountryContentProvider.CONTENT_URI, String.valueOf(id));
                // Setting uri to the data on the intent
                countryIntent.setData(data);
                // Open the activity
                startActivity(countryIntent);
            }
        });
        // Defining CursorAdapter for the ListView      
        mCursorAdapter = new SimpleCursorAdapter(getBaseContext(),
                android.R.layout.simple_list_item_1,
                null,
                new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1},
                new int[] { android.R.id.text1}, 0);
        // Setting the cursor adapter for the country listview
        mLVCountries.setAdapter(mCursorAdapter);
        // Getting the intent that invoked this activity
        Intent intent = getIntent();        
        // If this activity is invoked by selecting an item from Suggestion of Search dialog or 
        // from listview of SearchActivity
        if(intent.getAction().equals(Intent.ACTION_VIEW)){ 
            Intent countryIntent = new Intent(this, CountryActivity.class);
            countryIntent.setData(intent.getData());
            startActivity(countryIntent);
            finish();           
        }else if(intent.getAction().equals(Intent.ACTION_SEARCH)){ // If this activity is invoked, when user presses "Go" in the Keyboard of Search Dialog
            String query = intent.getStringExtra(SearchManager.QUERY);
            doSearch(query);
        }       
    }   
    private void doSearch(String query){
        Bundle data = new Bundle();
        data.putString("query", query);
        // Invoking onCreateLoader() in non-ui thread
        getSupportLoaderManager().initLoader(1, data, this);        
    }
    /** This method is invoked by initLoader() */
    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle data) {
        Uri uri = CountryContentProvider.CONTENT_URI;       
        return new CursorLoader(getBaseContext(), uri, null, null , new String[]{data.getString("query")}, null);   
    }
    /** This method is executed in ui thread, after onCreateLoader() */
    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor c) { 
        mCursorAdapter.swapCursor(c);       
    }
    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        // TODO Auto-generated method stub      
    }       
}

活动_searchable.xml
//这是我想在searchView下显示的列表项结果

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/lv_countries"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />    
</LinearLayout>

可搜索文件

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint"
    android:searchSettingsDescription="@string/search_settings"

    android:searchSuggestAuthority="in.wptrafficanalyzer.searchdialogdemo.CountryContentProvider"
    android:searchSuggestIntentAction="android.intent.action.VIEW"
    android:searchSuggestIntentData="content://in.wptrafficanalyzer.searchdialogdemo.CountryContentProvider/countries"
    android:searchSuggestSelection=" ?"
    android:searchSuggestThreshold="1"    

    android:includeInGlobalSearch="true" >
</searchable>

活动_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    
    tools:context=".MainActivity" >

    <SearchView
        android:id="@+id/searchView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:iconifiedByDefault="false"
        android:imeOptions="actionSearch" >

    </SearchView>

    <Button
        android:id="@+id/btn_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/searchView1"
        android:text="@string/search" />

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.searchdialogdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <!--  Activity with SearchDialog enabled -->
        <activity
            android:name="in.wptrafficanalyzer.searchdialogdemo.MainActivity"
            android:label="@string/app_name" >            
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- Enabling Search Dialog -->                      
            <meta-data 
                android:name="android.app.default_searchable"
                android:value=".SearchableActivity" />                        
        </activity>

        <!-- A Searchable activity, that handles the searches -->
        <activity 
            android:name=".SearchableActivity" >            
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data 
                android:name="android.app.searchable"
                android:resource="@xml/searchable"/>            
        </activity>
        <!--  Activity that shows the country details -->
        <activity android:name=".CountryActivity" />
        <!-- Content Provider to query sqlite database -->
        <provider 
            android:name=".CountryContentProvider"  
            android:authorities="in.wptrafficanalyzer.searchdialogdemo.CountryContentProvider"
            android:exported="true" />        
    </application>

</manifest>

再次,请我只是一个新手,如果我的问题有问题,我真的很抱歉,我喜欢编程,我只是想学习。 总之,非常感谢!!! 任何帮助将不胜感激!

只需参考此链接..

http://wptrafficanalyzer.in/blog/customizing-autocompletetextview-to-display-images-and-text-in-the-suggestion-list-using-simpleadapter-in-android/

没什么大不了的。 如果您知道 CustomListView,那么这对您来说很容易。

不明白整个问题,但也许你想忘记onSearchRequested(); 并使用您自定义的searchView更改它。 尝试这个,

除了MainActivity之外,您不需要更改代码中的任何内容。 如果你不想要onSearchRequested(); 出于某种原因……在这里……

如果您的操作actionbar有自定义searchView并在布局中使用它而不是searchView ,则可以使用以下代码:

public class MainActivity extends FragmentActivity{
    static SearchView searchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);

        //Your design here
        MenuItem menuItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) menuItem.getActionView();
        searchView.setIconifiedByDefault(false);
        searchView.setQueryHint("Type something...");
        int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
        View searchPlate = searchView.findViewById(searchPlateId);
        if (searchPlate!=null) {
            searchPlate.setBackgroundColor(Color.DKGRAY);
            int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
            TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
            if (searchText!=null) {
                searchText.setTextColor(Color.WHITE);
                searchText.setHintTextColor(Color.WHITE);
            }
        }

      //Maybe this is what you want
     // Associate searchable configuration with the SearchView
        SearchManager searchManager =
               (SearchManager) getSystemService(Context.SEARCH_SERVICE);
       searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

        return true;
    }
}

并在您res/menu/main.xml添加此

<item android:id="@+id/search"
   android:title="@string/search_title"
   android:icon="@drawable/ic_search"
   android:showAsAction="collapseActionView|ifRoom"
   android:actionViewClass="android.widget.SearchView" />

并尝试执行您的项目

或者如果你真的想在你的layout使用你的自定义searchView那么这个:

public class MainActivity extends FragmentActivity{
    static SearchView searchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        searchView = (SearchView)findViewById(R.id.searchView1);
        searchView.setQueryHint("Type Word...");
        int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
        View searchPlate = searchView.findViewById(searchPlateId);
        if (searchPlate!=null) {
            searchPlate.setBackgroundColor(Color.WHITE);
            int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
            TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
            if (searchText!=null) {
                searchText.setTextColor(Color.DKGRAY);
                searchText.setHintTextColor(Color.LTGRAY);

                //This is what you want?
                SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
                searchView.getRootView();//Notice that i change this
                searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
            }
        }       
}

参考::设置搜索...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM