java - Android - SearchView 在单个 fragment Activity 中不起作用

标签 java android

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

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

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

主页 Activity

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>  

AndroidManifest

<?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>

searchable.xml

<?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>

关于java - Android - SearchView 在单个 fragment Activity 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52720091/

相关文章:

android - keystore 更改密码详细信息?

android - okHTTP 无法找到可接受的协议(protocol)(android)

android - android 本身支持 Unicode 吗?

java - 读取和处理25GB的大文本文件

java - 为什么我的计数器不能正常计数?尽管我的 if 语句未填写,但它添加了 +1

java - 如何在 TextView 中使用 ClickableSpans 并且仍然能够水平滚动?

java - 组装 jar 后 - 没有名为 EntityManager 的持久性提供程序

java - 在 Java 中使用 Apache POI 读取上标 excel 文本

java - 如何将图像路径作为参数传递给从相机拍摄的图像

java - 从 Android 应用程序将数据发送到 Google 电子表格