我无法从EdiText(edText)获取整数值。我不知道为什么会出现此问题。将执行Catch下的部分而不是Try

   public class Ybus_Activity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ybus);
        //Creating Linear Layout
        final LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        final LinearLayout main = (LinearLayout)findViewById(R.id.android_main_layout);
        //Creating TextView
        TextView getData=new TextView(this);
        getData.setText("Enter the number of LineData : ");
        getData.setId(5);
        getData.setLayoutParams(params);
        main.addView(getData);
        //Creating EdiText
        final EditText edText = new EditText(this);
        edText.setId(3);
        edText.setLayoutParams(params);
        edText .setWidth(100);
        edText .setImeOptions(EditorInfo.IME_ACTION_NEXT);
        edText .setInputType(InputType.TYPE_CLASS_NUMBER);
        edText .setKeyListener(DigitsKeyListener.getInstance());
        edText .setMaxLines(1);
        main.addView(edText );
        final String ed=edText.getText().toString();
        //Creating Button for displaying integer from edText
        Button bt = new Button(this);
        bt.setText("Click to enter Linedata");
        bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        main.addView(bt);
        final TextView text = new TextView(this);
        bt.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                int i = 0;
                try{
                    i =Integer.parseInt(ed);
                    text.setText(i);
                }catch(NumberFormatException ex){
                    text.setText("Value at TextView is not a valid integer");
                }
            }
        });
        main.addView(text);
    }
}

最佳答案

嗨,您可以使用字符串在textview中显示,因此您可以执行以下操作

     bt.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String ed=edText.getText().toString();
                int i = 0;
                try{
                  i =Integer.parseInt(ed);
                 //setting value here
                 text.setText(String.valueof(i));
                 //or you can do like this
                 // text.setText(i+"");
                }catch(NumberFormatException ex){
                  text.setText("Value at TextView is not a valid integer");
                }
            }
        });

10-08 17:05