![](/img/trans.png)
[英]How to replace a string if not contained between '<' and '>'
[英]How to display username in a String contained in an array
我不知道如何在第二個活動中顯示上一個活動的用戶名。
我嘗試了很多方法,但是沒有一個方法可以讓我在字符串中顯示用戶名
這是MainActivity:
private EditText nameField;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameField = findViewById(R.id.nameEditText);
Button startButton = findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameField.getText().toString();
getusername(name);
}
});
}
private void getusername(String name) {
Intent intent = new Intent(this, OneShot.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
這是SecondActivity:
public static final String TAG = OneShot.class.getSimpleName();
private String name;
private int nextSentenceId = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_shot);
Intent intent = getIntent();
name = intent.getStringExtra(getString(R.string.key_name));
if (name == null || name.isEmpty()) {
name = "Player";
}
Log.d(TAG, name);
final int[] sentences = new int[]{R.string.page0, R.string.page2, R.string.page3, R.string.page4, R.string.page5 };
Button next= findViewById(R.id.next);
final TextView displayText= findViewById(R.id.displayText);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int limit = 5;
if(nextSentenceId < sentences.length){
displayText.setText(sentences[nextSentenceId]);
++nextSentenceId;
}
}
});
}
這些是int []中的字符串:
<string name="page0"> Hello %1$s </string>
<string name="page2"> Welcome into this application </string>
<string name="page3"> How are you ? </string>
<string name="page4"> How is the weather </string>
<string name="page5"> Is %1$s you\'re real name ? </string>
為什么沒有在字符串句子中傳遞用戶名,我該如何解決? 提前致謝。
更改:
數組中的字符串,以使其正確格式:
<string name="page0">Hello %s</string> <string name="page5">Is %s your real name?</string>
調用以根據上面的格式在TextView中設置文本:
displayText.setText(String.format(Locale.getDefault(), getString(sencences[nextSentenceId]), name));
您在int
數組中擁有的不是String
值,而是用於鏈接到所述String
資源的id。 您可以使用getResources().getString(R.string.yourstring)
獲得與ID關聯的String
資源(值getResources().getString(R.string.yourstring)
。
//So, instead of
//displayText.setText(sentences[nextSentenceId]);
//use
displayText.setText(getResources().getString(sentences[nextSentenceId]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.