如何在android中获取和设置字符串资源值

Tri*_*shi 3 string android android-resources

我宣布String:

<string name="Please">Please Select</string>
Run Code Online (Sandbox Code Playgroud)

res/values/Strings.xml.现在我想要访问这个String值,但我能得到的东西可以直到id不值如下:

 int i = findViewById(R.string.Please);
Run Code Online (Sandbox Code Playgroud)

但我想要的只是字符串的值Please.

谢谢你的所有答案,但我的问题有点大

我想做的只是用app_name显示日期

从你的所有答案我可以得到app_name字符串,但我是否可以设置此app_name与当前日期

<string name="app_name">My app</string>
Run Code Online (Sandbox Code Playgroud)

而且我也是这样设置我的

My app(in Left alignment)             Date (in right aligment)
Run Code Online (Sandbox Code Playgroud)

并且在第一个活动开始时我想设置app_name而不是每个活动;

我认为这可能有用,让我尝试一下

setResource().setString(R.string.Please);
Run Code Online (Sandbox Code Playgroud)

但没有setResource()方法对不起.

Bha*_*vin 10

试试这样吧

String temp = getResources().getString(R.string.Please);
Run Code Online (Sandbox Code Playgroud)


Fab*_*ook 7

你不能设置一个字符串,它的静态,并且不能在运行时更改,你想要做的就是这样

        Calendar cal = Calendar.getInstance();
        String date = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.YEAR);
        setTitle(date);
Run Code Online (Sandbox Code Playgroud)

你试图将标题设置为日期吗?

要拥有两个标题,有点困难,首先需要布局,调用此custom_title_1

这是该布局的xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView android:id="@+id/left_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/custom_title_left" />
    <TextView android:id="@+id/right_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="@string/custom_title_right" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

然后在调用UI之前在代码中,您需要调用它:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
Run Code Online (Sandbox Code Playgroud)

然后设置内容视图

然后调用它来设置标题:

getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
Run Code Online (Sandbox Code Playgroud)

现在您可以找到两个textView并设置文本:

TextView leftText = (TextView) findViewById(R.id.left_text);
TextView rightText = (TextView) findViewById(R.id.right_text);

Calendar cal = Calendar.getInstance();
String date = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.YEAR);
String app_name = getString(R.string.app_name);
leftText.setText(app_name);
rightText.setText(date);
Run Code Online (Sandbox Code Playgroud)


and*_*per 5

尝试这个。

String value = getResources().getString(R.string.Please);
Run Code Online (Sandbox Code Playgroud)