如何引用onClickListener的按钮?

时间:2014-07-12 03:38:25

标签: java android onclicklistener

我正在尝试创建一个Android应用,我想创建一个on click侦听器,这是我到目前为止。

public void amazonListener() {
amazonButton = (Button) findViewById(R.id.amazonButton);                
}

如你所见,我处于早期阶段,但在我第一次引用 amazonButton (在=符号之前)按钮的地方,它变成了红色文字,它说无法解析符号'amazonButton'的。另外,我在onCreate方法中引用了这个方法

2 个答案:

答案 0 :(得分:0)

您需要在声明变量时给出变量的类型。

Button amazonButton = (Button) findViewById(R.id.amazonButton);

另一种方法是在任何方法之外声明它(但不是初始化它),然后在以后初始化它。

Button amazonButton;
/* ... */
private void amazonListener() { 
    amazonButton = (Button) findViewById(R.id.amazonButton);                
} 

答案 1 :(得分:0)

这就是您创建按钮并为其设置点击监听器的方法。

public class MainActivity extends YouTubeFailureRecoveryActivity {

    Button amazonButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        amazonButton = (Button) findViewById(R.id.amazonButton);
        amazonButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //Define what should happen when the button is clicked. 
            }
        });
    }
}

您也可以将初始化放在一个方法中并调用该方法,就像您尝试过的那样:

public class MainActivity extends YouTubeFailureRecoveryActivity {

    Button amazonButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initializeViews();
    }

    private void initializeViews() {
        //Make sure you've declared the buttons before you initialize them. 
        amazonButton = (Button) findViewById(R.id.amazonButton);
        amazonButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //Define what should happen when the button is clicked. 
            }
        });

        // Add more Views initialization here ...
        ....
    }

}