1.String
可以在res/value/strings.xml中配置字符串,优点是方便批量修改字符串常量,同时因为xml是配置文件,所以修改后不用再编译。
strings.xml中定义string,名字+内容:
java文件中使用:
xml文件中使用:
类似地,colors.xml也是一样的配置和使用。
2.meta-data传送数据
在AndriodManifest.xml文件中配置,写在Activity内部:
一般来说,meta-data用在使用第三方的SDK的时候。
在java文件中使用meta-data:
package com.example.ch2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity7 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
TextView view = findViewById(R.id.tv);
PackageManager packageManager = getPackageManager();
try {
ActivityInfo activityInfo = packageManager.getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
Bundle metaData = activityInfo.metaData;
view.setText(metaData.getString("lunch"));
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
}
}
3.meta-data传递复杂信息
meta-data不仅有name和value属性,还有一个resource属性,可以指定一个xml文件,用于传递更加复杂的信息。
举例:APP在桌面时长按出现的快捷方式菜单
首先配置AndriodManifest.xml中的meta-data:
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts"/>
接着编写xml/shortcuts.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled = "true"
android:icon = "@drawable/img"
android:shortcutShortLabel = "@string/s1"
android:shortcutLongLabel = "@string/s1"
android:shortcutId = "s1"
>
<intent android:action="android.intent.action.VIEW"
android:targetPackage="com.example.ch2"
android:targetClass="com.example.ch2.MainActivity7"></intent>
<categories android:name = "android.shortcut.conversation"/>
</shortcut>
<shortcut
android:shortcutId = "s2"
android:enabled = "true"
android:icon = "@drawable/img"
android:shortcutShortLabel = "@string/s2"
android:shortcutLongLabel = "@string/s2"
>
<intent android:action="android.intent.action.VIEW"
android:targetPackage="com.example.ch2"
android:targetClass="com.example.ch2.MainActivity5"></intent>
<categories android:name = "android.shortcut.conversation"/>
</shortcut>
<shortcut
android:shortcutId = "s3"
android:enabled = "true"
android:icon = "@drawable/img"
android:shortcutShortLabel = "@string/s3"
android:shortcutLongLabel = "@string/s3"
>
<intent android:action="android.intent.action.VIEW"
android:targetPackage="com.example.ch2"
android:targetClass="com.example.ch2.MainActivity2"></intent>
<categories android:name = "android.shortcut.conversation"/>
</shortcut>
</shortcuts>
需要注意的是android:shortcutShortLabel和android:shortcutLongLabel 不能直接复制一个常量字符串,需要先去strings.xml中定义,再在赋值时引用变量名。
长按APP效果图:
点击选项,可以跳转到对应的Activity