In my code I have the xml string that I would like to replace in the java file with another string from the string.xml, if the TextView is clicked. Can I input a string from the string.xml file into the mainactity.java file?
//activity_main.xml
android:id="@+id/description"
android:text="description of activity"
//MainActivity.java
TextView moreInfo = (TextView) findViewById(R.id.description);
moreInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moreInfo.setText(@string/description_activity_main);)
}
});
Yes, you can. You're just doing it wrong. Here's what you should do:
moreInfo.setText(getString(R.string.description_activity_main));
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
</resources>
This application code retrieves a string:
String string = getString(R.string.hello);
You can use your string from string.xml
by using getResources()
which can be used after importing R
file as,
import com.example.R; // com.example should be replaced your package path
Then change as the following,
moreInfo.setText(getResources().getString(R.string.description_activity_main));
使用getString()
函数
getString(R.string.sting_name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.