簡體   English   中英

如何在 Kotlin 中的菜單項選擇上打開一個新頁面?

[英]How do I open a new page on menu item select in Kotlin?

我的應用程序中有一個選項菜單,其中包含一個項目:

菜單在main.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/action_about"
        android:icon="@android:drawable/ic_menu_info_details"
        android:orderInCategory="100"
        android:title="@string/action_about"
        app:showAsAction="never" />
</menu>

菜單似乎是在MainActivity.kt構建的:

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

我創建了一個簡單的 Activity,當從activity_about.xml定義的菜單中選擇 About 項時,我想顯示它:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".About">

    <TextView
        android:id="@+id/aboutView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:linksClickable="false"
        android:text="@string/author"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

以及About.kt的關聯類:

package com.example.rollme

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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

單擊“關於”菜單項時如何顯示“關於”活動?

您需要覆蓋方法onOptionsItemSelected並處理對您的項目的點擊。 Java示例:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.action_about) {
       startActivity(New Intent(this, About.class))
       return true;
    }else {
        return super.onOptionsItemSelected(item);
    }
}

在您的 MainActivity 中添加:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when(item.itemId)
    {R.id.action_about -> startActivity(Intent(this , About::class.java)) }
    return true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM