Android,我想在文本视图中更改一个单词
我有一个包含多个句子的字符串数组,如 嗨,我想谢谢你,诸如此类 嘿,别忘了给我打电话 等等 我有一个生成随机短语的按钮(我同意) 我想做的是,当用户单击按钮时,它应该将*替换为人员的实际姓名 如何更改string.xml中字符串数组列表中的特定字符 多谢各位 这是我的实际代码,我被困在基本上更改*的名称:Android,我想在文本视图中更改一个单词,android,textview,arrays,Android,Textview,Arrays,我有一个包含多个句子的字符串数组,如 嗨,我想谢谢你,诸如此类 嘿,别忘了给我打电话 等等 我有一个生成随机短语的按钮(我同意) 我想做的是,当用户单击按钮时,它应该将*替换为人员的实际姓名 如何更改string.xml中字符串数组列表中的特定字符 多谢各位 这是我的实际代码,我被困在基本上更改*的名称: Button generate; EditText friendName; TextView cannedPhrase; String[] randomPhrase; @Override p
Button generate;
EditText friendName;
TextView cannedPhrase;
String[] randomPhrase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgets();
}
private void initializeWidgets() {
// Initializes, button, EditText and TextView
generate = (Button)findViewById(R.id.buttonGenerate);
friendName = (EditText)findViewById(R.id.editTextFriendsName);
cannedPhrase = (TextView)findViewById(R.id.textViewRandomPhrase);
randomPhrase = getResources().getStringArray(R.array.canned_phrases);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onGenerate(View V){
String randomStr = randomPhrase[new Random().nextInt(randomPhrase.length)];
String friend = friendName.getText().toString();
cannedPhrase.setText(randomStr);
}
}如果您只是想用自己的名字替换一组字符,那么您可以像在onGenerate方法中那样调用String的replace方法:
String randomStr = ...
String friend = ...
randomStr = randomStr.replace("*", friend);
cannedPhrase.setText(randomStr);
在
strings.xml
中,将*
替换为字符串占位符%s
:
<string-array name="canned_phrases">
<item>"Hi %s, I wanted to thank you blah blah...."</item>
<item>"Hey %s, don't forget to call me...."</item>
</string-array>
“您好%s,我想感谢您诸如此类……”
“嘿%s,别忘了给我打电话……”
在代码中,使用:
cannedphase.setText(String.format(randomStr,friend))
这其实是三个问题。如何从文本视图中获取数据、如何设置数据以及如何更改字符串中的字符。看看你能为这三个部分找出什么,让我们知道你在这三个部分上的进展,以及你在哪里遇到了问题。看看我上面的代码,为什么会投反对票?我的问题怎么了?人们通常喜欢定义明确的问题,试图解决问题的特定部分。这似乎是一个“告诉我如何为我做我的工作”的问题,这里的人通常不喜欢这个问题。您的编辑有很大帮助,我将重点关注这样一个事实:您正在尝试将所有*字符更改为字符串中的一个单词,而忽略其他所有内容。考虑捕获replace()