格式化EditText输出时出错

时间:2013-10-03 09:24:43

标签: android formatting bundle

我已经修改了我的活动,使用名为round的自定义方法格式化EditText输出,但是当我在将结果设置为EditTexts时调用方法时,我收到错误: The method setText(CharSequence) in the type TextView is not applicable for the arguments (double)。我从中收集到使用2时添加settext的额外参数时出现问题,但我不确定如何输出结果。我的问题是在这种情况下,如何在使用此round函数时输出结果?

public class CalcResult extends MainActivity
{
    EditText result1,result2;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        result1 = (EditText)findViewById(R.id.mark1);
        result2 = (EditText)findViewById(R.id.mark2);


        Intent intent = getIntent();
        double mark1 = intent.getDoubleExtra("number1", 0);
        double mark2 = intent.getDoubleExtra("number2", 0);


        //set the variables on EditTexts like this :
        result1 = (EditText)findViewById(R.id.mark1);
        result2 = (EditText)findViewById(R.id.mark2);

        result1.setText(round(mark1,2));
        result2.setText(round(mark2,2));
    }

    public static double round(double value, int places) {
        if (places < 0)
            throw new IllegalArgumentException();

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }


}

3 个答案:

答案 0 :(得分:1)

使用:

result1.setText(String.ValueOf(round(mark1,2)));
result2.setText(String.ValueOf(round(mark2,2)));

答案 1 :(得分:1)

  

TextView类型中的方法setText(CharSequence)不是   适用于参数(双)

使用

double r1 = round(mark1,2);
result1.setText(String.valueOf(r1)); 
double r2 = round(mark2,2);
result1.setText(String.valueOf(r2)); 
当你有setText(CharSequence)返回的双倍时,

round(mark1,2)会将CharSequence作为参数。

java docs

public static String valueOf(double d)
Returns the string representation of the double argument.
The representation is exactly the one returned by the Double.toString method of one argument.

Parameters:
d - a double.
Returns:
a string representation of the double argument.
See Also:
Double.toString(double)

答案 2 :(得分:1)

// try this
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        result1 = (EditText)findViewById(R.id.mark1);
        result2 = (EditText)findViewById(R.id.mark2);

        Intent intent = getIntent();
        double mark1 = intent.getDoubleExtra("number1", 0);
        double mark2 = intent.getDoubleExtra("number2", 0);

        result1.setText(round(mark1,2));
        result2.setText(round(mark2,2));
    }

    public static String round(double value, int places) {
        if (places < 0)
            throw new IllegalArgumentException();

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
        return String.valueOf(bd.doubleValue());
    }