Getting decimal number from edittext

放肆的年华 提交于 2019-12-24 03:49:08

问题


I know something similar has already been asked, but I'm having some trouble to get a decimal number that come from keyboard.

My Java code in the onCreate method should be:

textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v)
    {
        //how should I get here the number from keyboard?
        //I think  I should be something like
        //double S0=textS0.getText()....
    }
});

And that's what my XML file contains

<EditText
       android:id="@+id/editS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:ems="10"
       android:hint="@string/S0"
       android:inputType="numberDecimal" />
<Button
       android:id="@+id/getS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/setS0" />
</LinearLayout>

回答1:


Just do this:

double S0 = Double.parseDouble(textS0.getText().toString());



回答2:


textS0=(EditText)findViewById(R.id.editS0);
Button btn_S0=(Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener() 
{
public void onClick(View v)
{

           double S0 = Double.parseDouble(textS0.getText().toString());
}
});



回答3:


May b you face null pointer exception in string so try this....

  1. get the number decimal from edittext using this

       Double BText=ParseDouble(String.valueOf(edittext.getText()));
    
  2. after that paste this code.. it prevents you from null pointer exception

    double ParseDouble(String strNumber) {
    if (strNumber != null && strNumber.length() > 0) {
        try {
            return Double.parseDouble(strNumber);
        } catch(Exception e) {
            return -1;
        }
    }
    else return 0;
    }
    


来源:https://stackoverflow.com/questions/16506756/getting-decimal-number-from-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!