我在类文件里是这样写的。
public class MainActivity extends Activity {
public Button submit;
public TextView tv1, tv2, tv3;
public int num1, num2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取view
submit = (Button) findViewById(R.id.submit);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
//设置监听器
OnClickListener btnl = new OnClickListener(){ //覆盖OnClic()方法
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//获取textview的值
num1 = Integer.parseInt(tv1.getText().toString());
num2 = Integer.parseInt(tv2.getText().toString());
//显示num1和num2的和
tv3.setText(String.valueOf(num1 + num2));
}
};
//将监听器和被监听对象相关联
submit.setOnClickListener((android.view.View.OnClickListener) btnl); }红色的这一行是系统提示自动的强制转换,如果没有强制转换就会报错,这是什么原因啊。求解。谢谢
public class MainActivity extends Activity {
public Button submit;
public TextView tv1, tv2, tv3;
public int num1, num2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取view
submit = (Button) findViewById(R.id.submit);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
//设置监听器
OnClickListener btnl = new OnClickListener(){ //覆盖OnClic()方法
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//获取textview的值
num1 = Integer.parseInt(tv1.getText().toString());
num2 = Integer.parseInt(tv2.getText().toString());
//显示num1和num2的和
tv3.setText(String.valueOf(num1 + num2));
}
};
//将监听器和被监听对象相关联
submit.setOnClickListener((android.view.View.OnClickListener) btnl); }红色的这一行是系统提示自动的强制转换,如果没有强制转换就会报错,这是什么原因啊。求解。谢谢
这样你实现的btnl 不是android.view.View.OnClickListener的实例把你的import xxx.OnClickListener改成import android.view.View.OnClickListener;