5.3

所花时间(包括上课):1

打码量(行):200

博客量(篇):1

了解到知识点:学习Action item

 

 <!-- res/layout/activity_main.xml -->

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

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

 

    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!"

        android:layout_centerInParent="true"

        android:textSize="18sp"/>

</RelativeLayout>

<!-- res/menu/menu_main.xml -->

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

    <item

        android:id="@+id/action_search"

        android:icon="@android:drawable/ic_menu_search"

        android:title="Search"

        android:orderInCategory="100"

        android:showAsAction="ifRoom"/>

    <item

        android:id="@+id/action_settings"

        android:title="Settings"

        android:orderInCategory="100"

        android:showAsAction="never"/>

</menu>

// src/main/java/com/example/actionitemapp/MainActivity.java

package com.example.actionitemapp;

 

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.menu_main, menu);

        return true;

    }

 

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle item selection

        switch (item.getItemId()) {

            case R.id.action_search:

                Toast.makeText(this, "Search selected", Toast.LENGTH_SHORT).show();

                return true;

            case R.id.action_settings:

                Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show();

                return true;

            default:

                return super.onOptionsItemSelected(item);

        }

    }

}

posted @ 2024-05-03 12:20  赵千万  阅读(3)  评论(0编辑  收藏  举报