在运行app时更改字符串

时间:2014-01-26 15:36:21

标签: android string

我制作的应用程序以用户输入密码的屏幕开头。我在底部有一个文字"You have 3 attempts remaining",并希望每次密码不正确时将其从3减少到2(我已经有一个IF else语句,我称之为新活动)如果密码正确并且可以将此方法添加到else)但我不确定如何更新字符串?

我正在考虑使用For循环并尝试过这个:

public String textAttempts(View view){
    String attemptsRemaining = getString(R.string.attempts_Remaining);
    int loopVal; 

    for(loopVal=1;loopVal>=0;loopVal--){
       String attmeptsRemaining =   
                   attemptsRemaining.replace(loopVal, loopVal); 
    }
    return attemptsRemaining;
}

然而,由于必须将int转换为字符串并且还使得replace语句不满意,它变得非常混乱。 有没有人有更好的方法呢?

字符串XML文件:

<resources>

<string name="app_name">Stock Control System FINAL</string>
<string name="action_settings">Settings</string>
<string name="enter_password">Enter Password</string>
<string name="edit_message">Enter a message</string>
<string name="button_confirm">Confirm</string>
<string name="title_activity_main">MainActivity</string>
<string name="title_activity_main_menu_passed">MainMenuPassed</string>
<string name="button_stock">Stock</string>
<string name="button_products">Products</string>
<string name="button_supplies">Incoming Supplies</string>
<string name="button_suppliers">Suppliers</string>
<string name="button_settings">Settings</string>
<string name="title_activity_main_stock">MainStock</string>
<string name="title_activity_main_menu">MainMenu</string>
<plurals name="attempts_remaining">
    <item quantity="one">You have one attempt remaining.</item>
    <item quantity="other">You have %d attempts remaining.</item>
</plurals>

</resources>

2 个答案:

答案 0 :(得分:1)

nr4bt的答案很好,但是在需要时它不会将句子从复数改为单数。你想要做的是:

strings.xml添加:

<plurals name="attempts_remaining">
        <item quantity="one">You have one attempt remaining.</item>
        <item quantity="other">You have %d attempts remaining.</item>
</plurals>

在您的代码中执行以下操作:

attemptsRemainingTextView.setText(getResources().getQuantityString(R.plurals.attempts_remaining, attempRemaining, attempRemaining));

详细了解Android plurals

答案 1 :(得分:0)

声明一个像

这样的全局变量
int attempCount;

每次检查尝试时,将计数增加1,并在textAttempts中设置此值。

// you can declare your R.string.attempts_remaining like "you have %s remaining attemp"
public String textAttempts(View view){
    String t= getString(R.string.attempts_Remaining);
    return String.format(t, "" + attempCount);
}