使用匿名类android获取edittext的输入

时间:2014-03-10 19:32:46

标签: java android math

长话短说我尝试制作应用以将Celsius转换为Fahrenheit并返回。我希望从编辑文本中获取输入,以便我可以将其用于我的数学,但我无法弄明白,也无法让按钮正常工作以关闭它。我想使用内部匿名类来进行计算并读入值,但又不知道该怎么做。有谁知道从哪里开始?

这是我所拥有的

package com.example.a4;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
 import android.content.DialogInterface.OnClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;

 public class MainActivity extends Activity implements TextWatcher {

EditText mt=(EditText) findViewById(R.id.et1), 
         mt2=(EditText) findViewById(R.id.et2);

Button bt = (Button) findViewById(R.id.btn1);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //mt=(EditText) findViewById(R.id.et1);
   // mt2=(EditText) findViewById(R.id.et2);
}

OnClickListener oclBtnOk = new OnClickListener() {


    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub

    }
  };


 /* 
   buttonExit.setOnClickListener(
       new View.OnClickListener() {
           public void onClick(View v) {
               System.exit(0);
        }
    }
);*/


@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    int c = Integer.parseInt(s.toString());

    ftoc(c);

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

}


 void ftoc(int c){
  int f = ((9/5)*c) + 32;

  mt2.setText(f);
 }



 /*
  @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, menu);
      return true;
  }
  */



 }

1 个答案:

答案 0 :(得分:0)

您需要将mt = (EditText)findViewById内容移回onCreate。然后,如果要使用匿名类,请执行以下操作:

mt.setOnClickListener(new OnClickListener() {
     public void onClick(View v) {
          ...
     }
});

此外,请确保您现在使用的是View.OnClickListener而不是DialogInterface.OnClickListener(请检查您的导入)。