将工具栏按钮合二为一 activity

implement toolbar buttons in one activity

我正在学习如何使用 Android Studio 和 Kotlin 语言。我创建了一个工具栏,其中有两个按钮(搜索和共享)。我在“搜索”按钮起作用的地方创建了一个 activity,在“分享”按钮起作用的地方创建了另一个 activity。现在,我想创建一个 activity 两个按钮都可以使用的地方。我该怎么办?

//toolbar
<?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"
    android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_menu"
        android:theme="@style/Theme.Training">
    <item
        android:id="@+id/search"
        android:icon="@drawable/ic_baseline_search_24"
        android:title="@string/search"
        app:showAsAction="ifRoom|withText"
        app:actionViewClass="android.widget.SearchView"/>
        <item
            android:id="@+id/share"
            app:showAsAction="ifRoom"
            android:title="@string/share"
            android:icon="@drawable/ic_baseline_share_24" />
</menu>

//search
package com.example.training
import android.R.layout.simple_list_item_1
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.SearchView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuItemCompat

class SearchActivity : AppCompatActivity() {
    private var listView: ListView? = null
    var list: ArrayList<String>? = null
    var adapter: ArrayAdapter<String>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)

        listView = findViewById<View>(R.id.listafrutta) as ListView
        list = ArrayList()
        list!!.add("Mango")
        list!!.add("Avocado")
        list!!.add("Papaya")
        list!!.add("Kiwi")
        list!!.add("Maracuja")
        list!!.add("Ananas")
        list!!.add("Lici")
        list!!.add("Banana")

        adapter = ArrayAdapter(this, simple_list_item_1, list!!)
        listView!!.adapter = adapter }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.main_menu, menu)
        val searchViewItem = menu.findItem(R.id.search)
        val searchView = MenuItemCompat.getActionView(searchViewItem) as SearchView
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                searchView.clearFocus()
                if(list?.contains(query)!!){
                    adapter?.filter?.filter(query)
                } else {
                    Toast.makeText(applicationContext, "No Match found",Toast.LENGTH_LONG).show()
                }
                return false
            }
            override fun onQueryTextChange(newText: String): Boolean {
                adapter!!.filter.filter(newText)
                return false
            }
        })
        return super.onCreateOptionsMenu(menu)
    }
}

//share
package com.example.training

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity

class ShareActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_share)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) { // uso switch case perché è possibile avere più icone
            R.id.share -> {
                val sharingIntent = Intent(Intent.ACTION_SEND)
                sharingIntent.type = "text/plain" // tipo di content da condividere
                val shareBody = "Body message" // Body del content
                val shareSubject = "Subject Here" // puoi condividere qualsiasi cosa
                sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody) // qui passo il body
                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject) // e poi passo il subject
                startActivity(Intent.createChooser(sharingIntent, "Share using"))
            }
        }
        return super.onOptionsItemSelected(item)
    }
}

为了在工具栏上同时拥有 searchView 和共享按钮,您的 activity 必须如下所示:

    class MainActivity : AppCompatActivity() {
    private var listView: ListView? = null
    var list: ArrayList<String>? = null
    var adapter: ArrayAdapter<String>? = null
    lateinit var searchView: SearchView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        listView = findViewById<View>(R.id.listafrutta) as ListView
        list = ArrayList()
        list!!.add("Mango")
        list!!.add("Avocado")
        list!!.add("Papaya")
        list!!.add("Kiwi")
        list!!.add("Maracuja")
        list!!.add("Ananas")
        list!!.add("Lici")
        list!!.add("Banana")

        adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list!!)
        listView!!.adapter = adapter
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        val searchViewItem = menu.findItem(R.id.search)
        searchView = MenuItemCompat.getActionView(searchViewItem) as SearchView
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                searchView.clearFocus()
                if (list?.contains(query)!!) {
                    adapter?.filter?.filter(query)
                } else {
                    Toast.makeText(applicationContext, "No Match found", Toast.LENGTH_LONG)
                        .show()
                }
                return true
            }

            override fun onQueryTextChange(newText: String): Boolean {
                adapter?.filter
                adapter!!.filter.filter(newText)
                return false
            }
        })
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.share -> {
                val sharingIntent = Intent(Intent.ACTION_SEND)
                sharingIntent.type = "text/plain" // tipo di content da condividere
                val shareBody = "Body message" // Body del content
                val shareSubject = "Subject Here" // puoi condividere qualsiasi cosa
                sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody) // qui passo il body
                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject) // e poi passo il subject
                startActivity(Intent.createChooser(sharingIntent, "Share using"))
                true
            }
            else -> {
                super.onOptionsItemSelected(item)
            }
        }
    }
}

所以基本上您是将您的两个实现合并为一个。请注意,我们已经创建了一个名为 searchView 的全局变量。我们创建了一个全局变量,以便能够访问 onOptionsItemSelected.

中创建的视图

我的菜单是这样的:

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/main_menu">
    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_search_category_default"
        android:title="search"
        app:showAsAction="always"
        app:actionViewClass="android.widget.SearchView"/>
    <item
        android:id="@+id/share"
        app:showAsAction="always"
        android:title="share"
        android:icon="@android:drawable/ic_menu_share" />
</menu>

我使用了 app:showAsAction="always" 以便始终显示它们。这不是一个好的做法,但我认为这是必要的。

如果您需要更多帮助,请告诉我