想要将 TextView
的文本设置为字符串,在我的 MainActivity
中设置如下:
String w1 = "Water";
在onCreate()
中设置TextView
:
tv = (TextView) findViewById(R.id.TextView);
想要将我的 MainActivity
中的 TextView
的文本设置为字符串 w1。
尝试过这个:tv.setText(w1)
,但不起作用。
我应该使用 string.xml 文件执行此操作,还是可以像我到目前为止所做的那样执行此操作?
如果我应该对字符串文件执行此操作,我应该如何执行此操作?
这是整个代码:
package name.verkaufsliste;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public TextView tv1;
public String w1 = "Water";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1= (TextView) findViewById(R.id.tv1);
tv1.setText(w1)
}
}
我的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="name.MainActivity">
<TextView
android:id="@+id/TextView"
android:layout_width="150dp"
android:layout_height="30dp"
android:ems="10" />
最佳答案
在strings.xml
<resources>
<string name="water">water</string>
</resources>
然后
tv.setText(R.string.water);
编辑:
不仅仅是喜欢它,这是行不通的。您可能想要执行以下操作
tv.setText(getResources().getString(R.string.water));
关于java - Android Studio setText 并在代码中设置字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46713418/