摆脱android中的“==”语法错误

时间:2011-06-06 12:26:32

标签: java android

elseif(v == button2)行给出错误,指出“令牌上的语法错误'==',删除此令牌”。我从这个网站的主题“变量OnClick监听器android”中得到了这个想法。谁能告诉我如何使用它?

这是我的代码:

    View.OnClickListener yourListener = new View.OnClickListener(){
        public void onClick(View v){
            if( v ==  button1){
                new AlertDialog.Builder(this)
                .setTitle("Paracettamol")
                .setMessage("This medicine is generally used to cure Fever")
                .setNeutralButton("OK", null)
                .show();}
            }
        elseif( v == button2){
            new AlertDialog.Builder(this)

        .setTitle("sertraline")
        .setMessage("This medicine is generally used to cure Head aches")
        .setNeutralButton("OK", null)
        .show();

        }



        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
        }  ; 
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
        }

上面提到的问题的答案有以下代码:

Button btn1, btn2;
public void onCreate(Bundle b)
{
    // here you do normal things like assigning a
    // content view to the activity, initiate buttons, etc.

    // then you assign the same listener to both buttons
    btn1.setOnClickListener(yourListener);
    btn2.setOnClickListener(yourListener);
}

// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
    public void  onClick  (View  v){
        if( v == btn1 ){
            // do something 
        }
        elseif( v == btn1 ){
            // do another thing
        }
    }
};

2 个答案:

答案 0 :(得分:8)

你可能错过了else之间的空格,如果 - “elseif(v == button2)”

答案 1 :(得分:1)

...啊

您的代码示例很乱......

我重新格式化并纠正错误。现在应该可以了。

View.OnClickListener yourListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (v == button1) {
                new AlertDialog.Builder(v.getContext())
                        .setTitle("Paracettamol")
                        .setMessage(
                                "This medicine is generally used to cure Fever")
                        .setNeutralButton("OK", null).show();
            } else if (v == button2) {
                new AlertDialog.Builder(v.getContext())
                        .setTitle("sertraline")
                        .setMessage(
                                "This medicine is generally used to cure Head aches")
                        .setNeutralButton("OK", null).show();
            }

        }
    };

下次你问问题会更准确吗?