Проблемы с меню на панели инструментов - PullRequest
0 голосов
/ 18 сентября 2018

В моем приложении много фрагментов, каждый фрагмент имеет кнопку меню и значок на панели инструментов.

После того, как я использую панель действий и значок работают, но когда я заменяю панель действий панелью инструментов, меню не работает.

Моя панель инструментов состоит из: меню и одной кнопки.

XML-код:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar_home"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/AppTheme.NoTitle"
    app:popupTheme="@style/AppTheme">

    <ImageButton
        android:id="@+id/toolbar_button"
        android:src="@drawable/login"
        android:layout_width="30dp"
        android:layout_height="40dp"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_alignParentEnd="true"/>

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Maintenance"
            android:textColor="@color/WHITE" />

</android.support.v7.widget.Toolbar>

</RelativeLayout>

Пожалуйста, помогите мне, я не нашел ошибку.

Я прилагаю код:

class FragmentDiagnosticsTableViewController : Fragment(), SwipeRefreshLayout.OnRefreshListener {

lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
lateinit var elementList: ListView
lateinit var elementListAdapter: FragmentDiagnosticsTableViewController.ElementAdapter
lateinit var toolbarTopDiagnostic : Toolbar


companion object {

    fun newInstance(): Fragment {
        var fb: FragmentDiagnosticsTableViewController = FragmentDiagnosticsTableViewController()
        return fb
    }
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    val rootView = inflater.inflate(R.layout.fragment_diagnostic, container,
            false)

    var builder = StrictMode.VmPolicy.Builder()
    StrictMode.setVmPolicy(builder.build())

    mContext = activity as MaintenanceTableViewController
    mSwipeRefreshLayout = rootView.findViewById<SwipeRefreshLayout>(R.id.swipeRefresh)
    mSwipeRefreshLayout.setOnRefreshListener(this)
    elementList = rootView.findViewById<ListView>(R.id.elementList)
    toolbarTopDiagnostic = rootView.findViewById(R.id.my_toolbar_diagnostic) as Toolbar
    toolbarTopDiagnostic.inflateMenu(R.menu.men_search)

    val activity = activity as AppCompatActivity?

    if (activity != null) {

        activity.setSupportActionBar(toolbarTopDiagnostic)
        activity.setTitle("")


    }


    var title = rootView.findViewById<TextView>(R.id.toolbar_title)
    title.setText("Diagnostic")



    val btn_diagnostic= toolbarTopDiagnostic.findViewById(R.id.toolbar_button_diagnostic) as ImageButton


    //(activity as AppCompatActivity).supportActionBar?.title = "Diagnostics"
    setHasOptionsMenu(true)

    DiagnosticsTableViewController().loadFileCsv(mContext)
    elementListAdapter = ElementAdapter(context!!, totalDiagnosticEntries)
    elementList.adapter = elementListAdapter

    return rootView

}

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {

    inflater.inflate(R.menu.men_search, menu)

    val searchItem = menu.findItem(R.id.action_search)
    val searchView = searchItem.actionView as SearchView
    searchView.setQueryHint("Search View Hint")

    searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {

        override fun onQueryTextSubmit(query: String): Boolean {
            //Task HERE
            return false
        }

        override fun onQueryTextChange(newText: String): Boolean {


            if (TextUtils.isEmpty(newText)) {
                elementListAdapter.filter("")
                elementList.clearTextFilter()
            } else {
                elementListAdapter.filter(newText)
            }

            return false
        }
    })

    return super.onCreateOptionsMenu(menu, inflater)

}

override fun onOptionsItemSelected(item: MenuItem): Boolean {

    try {
        if (item.itemId == R.id.shareButton) {
            var intentShareFile = Intent(Intent.ACTION_SEND)
            val fileWithinMyDir = filePathMessageLogger
            try {
                if (fileWithinMyDir != null) {
                    if (fileWithinMyDir.exists()) {
                        intentShareFile.setType("text/plain")
                        val fileURI = FileProvider.getUriForFile(activity!!, "com.example.saradalmonte.pocketserviceandroid", fileWithinMyDir!!)
                        intentShareFile.putExtra(Intent.EXTRA_STREAM, fileURI)
                        intentShareFile.putExtra(Intent.EXTRA_TEXT, "File Csv")
                        startActivity(Intent.createChooser(intentShareFile, "Share file"))
                        onStop()
                        return true
                    } else {
                        Toast.makeText(activity, "Error File not Exist", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                Toast.makeText(activity, "Error File not Exist", Toast.LENGTH_SHORT).show()
            }
        }

        else if (item.itemId == R.id.delete) {

            val fileWithinMyDir = filePathMessageLogger
            if (fileWithinMyDir != null) {
                if (fileWithinMyDir.exists()) {
                    fileWithinMyDir.delete()
                    totalDiagnosticEntries.clear()
                    elementListAdapter = ElementAdapter(context!!,totalDiagnosticEntries )
                    elementList.adapter = elementListAdapter

                }
            }
        }
        else if(item.itemId == R.id.toolbar_button_diagnostic){


            var intent = Intent(activity, LoginIn::class.java)
            startActivity(intent)
            onDestroy()

        }
    } catch (e: Exception) {
        Toast.makeText(activity, "Error File not present", Toast.LENGTH_SHORT).show()
    }
    return true
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    if (view != null) {
        super.onViewCreated(view, savedInstanceState)
        elementListAdapter = ElementAdapter(context!!, totalDiagnosticEntries)
        elementList.adapter = elementListAdapter


    }
}

1 Ответ

0 голосов
/ 18 сентября 2018

Вы должны установить supportActionBar в вашем activity

Добавьте это в onCreate() вашего activity:

setSupportActionBar(my_toolbar_home)
supportActionBar?.setDisplayShowTitleEnabled(false)
...