我正在为Android编写简单的计算器,我想将SubClass创建为适用于中等操作的主类。但点击按钮Toast
后,不显示任何消息,ButtonClickListener
不起作用。
我的源代码:
package ir.pishguy.tsms.peamoncalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static ir.tuxworld.tsms.peamoncalculator.R.layout.*;
public class MyActivity extends ActionBarActivity {
private String Operation;
private float NumberBf;
private EditText Scr;
private ButtonClickListener btnClick;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_my);
Scr = (EditText) findViewById(R.id.editText);
int idList[]={
R.id.button0,R.id.button1,R.id.button2,
R.id.button3,R.id.button4,R.id.button5,
R.id.button6,R.id.button7,R.id.button8,
R.id.button9,R.id.buttonEq,R.id.buttonDiv,
R.id.buttonClear,R.id.buttonSum,R.id.buttonTafrig
};
for (int id:idList){
View v= (View) findViewById(id);
System.out.println( id );
v.setOnClickListener(btnClick);
}
}
// New Class ButtonClickListener
private class ButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CLICKED !!",
Toast.LENGTH_LONG).show();
}
}
}
答案 0 :(得分:2)
添加一行:
btnClick = new ButtonClickListener();
for (int id:idList) {
...
你从未真正实例化过你的ButtonClickListener。
答案 1 :(得分:0)
尝试如下,
v.setOnClickListener(btnClick);
private OnClickListener btnClick= new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT).show();
}
};