【问题标题】:TextView/editText value changeTextView/editText 值变化
【发布时间】:2013-12-01 04:05:59
【问题描述】:

我有一个按钮,当按下该按钮时,将在单独的活动中将 TextView 的值更改为 1 --,但是当它只工作一次时,除非我放入一个新的,否则它将无法再次工作editText 值,那么它只能再次工作一次。

所以如果我输入10 然后onClick .Text-- 它将把它带到9 然后如果我onClick .Text-- 再次它仍然会显示9。也许你能看出我做错了什么?

 public void onClick(View v) {
             pref = getSharedPreferences("prefs", Context.MODE_PRIVATE);{

        CaAdd.amnt.setText(String.valueOf(CaAdd.amountt-1));
        newone = Integer.toString(CaAdd.amountt-1);
        Editor editor = pref.edit();
        res = "You have"  +" " + (String.valueOf(CaAdd.amountt-1))+" " + "Life left!";
        editor.putString("new",newone);
        editor.commit();
        Toast.makeText(getApplicationContext(), res ,Toast.LENGTH_SHORT).show();

ActivityCaAdd持有TextView和EditText:

    public void onClick(View v){


        Editor editor = pref.edit();

amountt++;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);



editor.putString("numbers", amountText);
editor.commit();





    }
});
ImageButton decrease = (ImageButton)mDateTimeDialogView.findViewById(R.id.decrease);
decrease.setOnClickListener(new OnClickListener(){

    public void onClick(View v){




        Editor editor = pref.edit();
      amountt--;
      amountText = Integer.toString(amountt);
      amountedit.setHint(amountText);
      amnt.setText(amountText);
      amount = amnt.getText().toString();
      editor.putString("numbers", amountText);
      editor.commit();

    }
         });

编辑:像这样?

     pref = getSharedPreferences("prefs", Context.MODE_PRIVATE);{
  int   Am =    pref.getInt("numbers", Integer.valueOf(CaAdd.amountt));
CaAdd.amnt.setText(Am);
  Am--;

         pill = Integer.toString(Am);

        Editor editor = pref.edit();
        res = "You have"  +" " + (String.valueOf(CaAdd.amountt-1))+" " + "Life left!";
        editor.putString("new",pill);
        editor.commit();
        Toast.makeText(getApplicationContext(), res ,Toast.LENGTH_SHORT).show();

【问题讨论】:

    标签: android textview int android-edittext


    【解决方案1】:

    问题在于您保存变量以增加递减值的方式。 在 onclick 之后,您将从 edittext 获取值并存储,但您要递减的值是 amountt 变量。您需要从首选项中获取值并减少它,显示它并保存到首选项

    【讨论】:

    • 谢谢哥们,但我很困惑,我应该改哪个?我以为我正在保存amountt 的字符串值,增加和减少然后减少相同的int?(CaAdd.amountt)。我也许pref.getString("numbers",amountText); then decrease that? I think I've tried that but I can not --`一个字符串只有一个int。
    • 而不是可变的直接读取值形式的偏好,减少它并显示它,然后保存
    • 呸,我还是听不懂你能不能给我一些示例代码来说明你的意思?