2014-09-02 150 views
1

我想在用户将东西添加到购物车时更改TextView。初始值为0.00,并且在用户添加项目时,将其添加到值中。点击允许用户选择项目的按钮时,弹出AlertDialog对话框。在Android中更改TextView的值

我的问题是一个java.lang.StringToReal.invalidReal错误。我认为我可能没有正确理解TextVeiw的价值,但我不完全确定。

感谢任何人看着这个。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      builder = new AlertDialog.Builder(MainActivity.this); 
      builder.setTitle(R.string.pickItem); 
      builder.setItems(R.array.items, new DialogInterface.OnClickListener(){ 
       public void onClick(DialogInterface dialog, int which) { 

        CartItems ci = new CartItems(); 
        ci.setItem(which); 
        ci.setPrice(which); 
        cart.add(ci); 

        totalPriceTV = (TextView)findViewById(R.id.textView2); 

        double totalPrice = Double.parseDouble(totalPriceTV.toString()); 
        totalPrice += ci.getPrice(); 
        String newTotal = new Double(totalPrice).toString(); 
        totalPriceTV.setText(newTotal); 

        } 
      }); 
      builder.create(); 
      builder.show(); 

     } 

    }); 

    } 
+0

发布整个错误 – 2014-09-02 02:25:46

+0

也许使用totalPriceTV.getText();而不是totalPriceTV.toString()? – Jerry 2014-09-02 02:29:01

回答

2

为了改变在Android上TextView的文本只是使用普通的geters和setter方法:

TextView.getText(); 
TextView.setText("text"); 

既然你与数字打交道,我建议你使用DecimalFormat当解析一个double到string。您可以轻松定义数字格式(即逗号后的数字或分隔符的数量)

DecimalFormat df = new DecimalFormat("###,###.00"); 
String price = df.parse(someDouble); 
textView.setText(price); 

对于这些数字:234123.2341234 12.341123DecimalFormat会给你以下结果:

234,123.2312.34

+0

就是这样。感谢您向我指出这一点。 – WeVie 2014-09-02 03:11:17

1

只要使用totalPriceTV.setText(“”+ totalPrice);

totalPriceTV.setText(将String.valueOf(totalPrice));

3

在这一行

double totalPrice = Double.parseDouble(totalPriceTV.toString()); 

变化totalPriceTV.toString()totalPriceTV.getText().toString(),然后再试一次。

+0

就是这样。谢谢! – WeVie 2014-09-02 03:11:47

1

从页摘自:http://developer.android.com/reference/android/view/View.html#toString()

在API级别1 返回包含此对象的简明的,人类可读的描述的字符串。鼓励子类覆盖此方法并提供一个考虑对象类型和数据的实现。默认实现等效于以下表达式:

getClass().getName() + '@' + Integer.toHexString(hashCode()) 

因此,您应该使用getText();

即:

totalPriceTV.getText()