将方法实现到按钮侦听器时出错

时间:2012-08-22 04:39:34

标签: java android eclipse

我尝试将该方法实现到我的Button onClickListener中,然后我得到了Syntax Error

以下是我的代码:

// button click event
btnCreateNewEvent.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
// Checking for server respond
if (serverRespond() == false) {
           //DO SOMETHING
}

以下是ServerRespond方法

之外的onCreate
// Check server respond    
public boolean serverRespond() {
boolean success = false;
    try {
        URL url = new URL(url_create_event);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.connect();
        if (urlcon.getResponseCode() == 200) {
            success = true;
        }
    } catch (Exception e) {
        Log.e(create_error.toString(), "Server is not responding");
    }
    return success;
}

错误:在if(serverRespond()==true){

"The method serverRespond() is undefined for the type new View.OnClickListener(){}"

3 个答案:

答案 0 :(得分:3)

您可以通过以下方式访问:

YourActivity.this.serverRespond()

答案 1 :(得分:1)

我认为你是按照以下方式调用serverRespond()方法:

this.serverRespond();

并且由于此方法在实现OnClickListener的类中,它将在此类或OnClickListener中搜索此方法。将其更改为:

serverRespond();

YourActivity.this.serverRespond()

根据Michel-F的回答。 Portzert。

答案 2 :(得分:1)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (serverRespond() == false) {
                Toast.makeText(getApplicationContext(), "onClick",
                        Toast.LENGTH_LONG).show();
            }

        }
    });

}



public boolean serverRespond() {
    Toast.makeText(getApplicationContext(), "serverRespond",
            Toast.LENGTH_LONG).show();
    return false;
}