第一行代码第三版 第三章intent

前言

大伙应该会觉得这一章特别简单,可是为啥我要再专门写一下这章的代码呢
原因是想记录一下在activity中使用menu还有将字符串的内容放在res/strings.xml的文件中的用法。
在这里插入图片描述在这里插入图片描述在这里插入图片描述
在这里插入图片描述



代码

在这里插入图片描述

在res目录下新建menu文件夹,然后新建一个main.xml的文件

<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/add_item"
        android:title="Add"
        tools:ignore="HardcodedText" />
    <item
        android:id="@+id/remove_item"
        android:title="Remove"
        tools:ignore="HardcodedText" />
</menu>

activity.xml中:(注意这里的android:text="@string/test_view")

<?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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test_view"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

strings.xml中:

<resources>
    <string name="app_name">classTest</string>
    <string name="test_view">Hello android!</string>
    <string name="click_add">you clicked add!</string>
    <string name="click_remove">you clicked remove!</string>
</resources>

最后看看MainActivity.kt:

package com.example.classtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    
    

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

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    
    
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    
    
        when(item.itemId) {
    
    
            R.id.add_item -> Toast.makeText(this, R.string.click_add, Toast.LENGTH_SHORT).show()
            R.id.remove_item -> Toast.makeText(this, R.string.click_remove, Toast.LENGTH_SHORT).show()
        }
        return true
    }
}

其中,注意一下这里的 R.string.click_add 和 R.string.click_remove 的用法。

R.id.add_item -> Toast.makeText(this, R.string.click_add, Toast.LENGTH_SHORT).show()
R.id.remove_item -> Toast.makeText(this, R.string.click_remove, Toast.LENGTH_SHORT).show()



结语

最后附带一个AlertDialog的实现的链接,觉得写得还是挺不错的.Kotlin Android AlertDialog

猜你喜欢

转载自blog.csdn.net/weixin_43850253/article/details/109226541