Android - OnClickListener - 未被调用的构造函数

时间:2012-09-26 14:58:12

标签: java android constructor onclick onclicklistener

这是我的第一个问题。通常我可以通过Gogle找到我的答案,这通常只会带我到stackoverflow,但这最终让我足够提问我自己的问题,可能很明显没有人需要问过它!

无论如何,这不是特别的。试着抓住onlicklisteners。在这种情况下,特别是内部类onclicklisteners

问题:为什么程序会跳过MathButtonClicked的构造函数? 我是CharSequence,但构造函数永远不会被调用(我通过logcat知道)。

public class Main extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button mathButton = (Button) findViewById(R.id.mathButton);
    EditText et = (EditText) findViewById(R.id.inputText);
    CharSequence inputText = et.getText().toString();


    mathButton.setOnClickListener(new MathButtonClicked(inputText));
}

private class MathButtonClicked implements OnClickListener {
    private CharSequence receivedText;

    public MathButtonClicked(CharSequence inputText) {
        this.receivedText=inputText;
        Log.d("Constructor", " " + receivedText);
    }



    public void onClick(View v) {
        Log.d("Onclick", " " + receivedText);
        Intent intent = new Intent(Main.this, Math.class);
        intent.putExtra("inputText", getText());
        startActivity(intent);          
    }

    public CharSequence getText(){
        return receivedText;
    }
    }//end inner class
} //end main

如果参数与参数匹配,是否总是调用构造函数? @ _ @

此外,我要完成的是将EditText视图中的文本传递给新意图。

我可以通过在EditText中创建OnClick对象来实现此目的,但我想在main方法中创建它,然后将信息传递给OnClick

谢谢!

1 个答案:

答案 0 :(得分:0)

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button mathButton = (Button) findViewById(R.id.mathButton);
EditText et = (EditText) findViewById(R.id.inputText);
CharSequence inputText = et.getText().toString();



 mathButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                     String receivedText=inputText;
         Log.d("Onclick", " " + receivedText);
                     Intent intent = new Intent(getApplicationContext(), Math.class);
                     intent.putExtra("inputText", receivedText);
                     startActivity(intent);

        }
    });