繁体   English   中英

Android - SearchView 在单个片段活动中不起作用

[英]Android - SearchView not working in single fragment activity

大家早上好,我正在尝试通过实现SearchView在具有搜索功能的单个活动中实现搜索功能。 从 UI 方面来看,一切正常。 但与我发现的几乎所有示例不同, SearchView不会启动另一个活动,而是应该向名为HomeActivity的单个正在运行的活动发送请求。

按照我在 Android 开发者网站和其他来源上找到的一些文档,我尝试像下面那样做。 通常,我应该在“ onNewIntent ”事件中处理搜索请求,但它从未被调用。 输入文本后单击按钮无效(它只是关闭键盘)。

我是 Android 开发的初学者,可能错过了一些简单的东西。 你能帮我么 ?

家庭活动

public class HomeActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {

    private FrameLayout myFrameLayout;
    private Fragment fragmentContracts, fragmentHardware, fragmentMaps, fragmentUsers;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;

        switch (item.getItemId()) {
            // Switch to fragment ...
        }
        return loadFragment(fragment);
    }
};

private void handleIntent(Intent intent) {

    Log.i("LOG_myapp", "Called new intent !!!");
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        //use the query to search your data somehow
        String msg = MessageFormat.format("Search query = {0}", query);
        Log.i("LOG_myapp", msg);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(query)
                .setTitle("Search request");
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

@Override
protected void onNewIntent(Intent intent){
    // *** NEVER CALLED :( ***
    Log.i("LOG_myapp", "Event onNewIntent raised");
    handleIntent(intent);
}

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

    myFrameLayout = (FrameLayout)findViewById(R.id.MyFrameLayout);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    Fragment defaultFragment = new places();
    defaultFragment.setRetainInstance(true);
    loadFragment(defaultFragment);

    Toolbar toolbar = (Toolbar)findViewById(R.id.activity_main_toolbar);
    setSupportActionBar(toolbar);

    handleIntent(getIntent());
}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.application, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager =
            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =
            (SearchView) menu.findItem(R.id.MenuItemSearch).getActionView();
    searchView.setSubmitButtonEnabled(true);
    ComponentName componentName = new ComponentName(this, HomeActivity.class);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()) {
        case R.id.MenuItemSettings:
            Intent intent = new Intent(this, preferences.class);
            startActivity(intent);
            break;
    }
    return true;
}

@Override
public boolean onQueryTextChange(String s){
    Log.i("LOG_myapp","Search query: " + s);
    return true;
}

@Override
public boolean onQueryTextSubmit(String s){
    Log.i("LOG_myapp","Submitted search query: " + s);
    return true;
}

private boolean loadFragment(Fragment fragment) {
    //switching fragment
    if (fragment != null) {
        try {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.MyFrameLayout, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    return false;
}

}

菜单.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/MenuItemSearch"
        android:title="Search"
        android:icon="@drawable/baseline_search_white_18dp"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
    <item android:id="@+id/MenuItemSettings"
        android:icon="@drawable/baseline_settings_white_18dp"
        app:showAsAction="always"
        android:title="Settings"/>
</menu>  

安卓清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vermilionenergy.myapp">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop">
            <intent-filter>
                <!--action android:name="android.intent.action.MAIN" /-->
                <action android:name="android.intent.action.SEARCH"/>
                <category android:name="android.intent.category.DEFAULT" />
                <!-- category android:name="android.intent.category.LAUNCHER" / -->
            </intent-filter>
            <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/>
            <meta-data android:name="android.app.default_searchable" android:value=".HomeActivity" />
        </activity>
        <meta-data android:name="android.app.default_searchable" android:value=".HomeActivity" />
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />


        <activity
            android:name=".maps"
            android:label="@string/title_activity_maps" />
        <activity
            android:name=".preferences"
            android:label="Preferences" />
        <!-- activity android:name=".users" / -->

        <activity android:name=".SplashScreenActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".TextActivity"></activity>
    </application>

</manifest>

可搜索文件

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="myapp"
    android:hint="Search items"
    >
</searchable>

我终于自己找到了解决方案。 看起来 searchable.xml 中的直接字符串不起作用。 我用下面的变量替换了它们并且它起作用了:)

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

暂无
暂无

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

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