如何为onClickListener引用按钮



我正在尝试创建一个Android应用程序,我想创建一个点击监听器,这是我到目前为止所拥有的。

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

正如你所看到的,我在非常早期的阶段,但当我第一次引用amazonButton(在=符号之前)按钮时,它变成了红色文本,它说不能解析符号'amazonButton'。另外,我在onCreate方法

中引用了这个方法

这就是创建按钮并为其设置单击侦听器的方法。

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 ...
        ....
    }
}

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

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

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

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

最新更新