【问题标题】:Android, I want to change a word in a textviewAndroid,我想在文本视图中更改一个单词
【发布时间】:2014-02-04 21:33:02
【问题描述】:

我有一个包含多个句子的字符串数组,例如

*,我想谢谢你等等等等......

*,别忘了给我打电话....

等等……

我有一个生成随机短语的按钮(我同意)

我想要做的是当用户单击按钮时,它应该将 * 替换为人的实际姓名。

如何从 string.xml 中的字符串数组列表中更改特定字符?

谢谢

这是我的实际代码,我主要是按名称更改 *:

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);

}

}

【问题讨论】:

  • 这真的是3个问题。如何从文本视图中获取数据,如何设置,如何更改字符串中的字符。看看你能解决这 3 个部分的问题,让我们知道你在这三个部分上的工作进展情况,以及你遇到问题的地方。
  • 看我上面的代码
  • 为什么投反对票?我的问题有什么问题?
  • 人们通常喜欢定义明确的问题,试图解决问题的特定部分。这似乎是一个“告诉我如何为我做我的工作”的问题,这里的人们通常不喜欢这个问题。您的编辑有很大帮助,我将重点关注您正在尝试将所有 * 字符更改为字符串中的一个单词,而忽略其他所有内容。

标签: android textview arrays


【解决方案1】:

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>

在您的代码中,使用String#format(String, Object...):

cannedPhrase.setText(String.format(randomStr, friend))

【讨论】:

    【解决方案2】:

    如果你只是想用你的名字替换一个集合字符,那么你可以在你的 onGenerate 方法中调用 String 的 replace 方法:

    String randomStr = ...
    String friend = ...
    randomStr = randomStr.replace("*", friend);
    cannedPhrase.setText(randomStr);
    

    【讨论】:

    • 考虑捕获replace()的结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2022-11-03
    • 2021-09-10
    相关资源
    最近更新 更多