如何从文本字段中获取文本

时间:2014-07-19 23:35:07

标签: java android

我想创建一个可以从文本字段(id etxt1)获得测试分数的应用程序,点击一个按钮就可以显示其他文本字段中的成绩(id etxt2)。

标记为A级100-91。

标志着B级90-81。

标志着C级80-71。

等等。

以及如何使用"> ="的事情。

这是我的代码:

Button bt1;
EditText etxt1;
EditText etxt2;
char grade = 0;
int score;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activitywhatsyourgrade);
    bt1 = (Button) findViewById(R.id.button1);
    etxt1 = (EditText) findViewById(R.id.testscore);
    final int score = etxt1.getTextAlignment();
    etxt2 = (EditText) findViewById(R.id.editText2);
    bt1.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (score == 90){
                etxt2.setText("A1");
            }
            else if (score ==80){
                etxt2.setText("A2");
            }
        }
    }); 
}    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_activitywhatsyourgrade, menu);
    return true;    
}

2 个答案:

答案 0 :(得分:0)

String a = etxt1.getText().toString();
etxt2.setText(a);

答案 1 :(得分:0)

我想在Mike Yaworski's answer

中添加修正案

虽然这段代码是正确的,但他给了......

@Override
public void onClick(View v) {

    String strScore = etxt1.getText().toString();

    int score = Integer.parseInt(strScore);

    ...

... getText()可以存在一个根本缺陷,如果该字段留空,则会返回null。那是因为它没有返回String - 它返回Editable;因此,你必须打电话给toString()

这是我对它的更正。注意,我必须从GUI中的2个项目中获取文本,因此我将逻辑分离为返回给定private的{​​{1}}方法

String
相关问题