-1

我正在尝试在 android 中实现一个微调器,当我这样做时,我遇到了这个奇怪的语法错误,我无法解决它。

我正在编写的代码:

public class AddContact extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.add_contact, menu);
        return true;
    }

    Spinner spinner = (Spinner) findViewById(R.id.contact_number_array);

    //Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> Adapter = ArrayAdapter.createFromResource(this, R.array.phone_array, android.R.layout.simple_spinner_item);

    //Specify the layout to use when the list of choices appears
    Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}

当我在写“Adapter.setDropDownViewResource ....”时,我收到了这个奇怪的错误,这是堆栈跟踪:

 Multiple markers at this line
    - Syntax error, insert "}" to complete ClassBody
    - Syntax error, insert "enum Identifier" to complete 
     EnumHeaderName
    - Syntax error on token "Adapter", delete this token
    - Syntax error, insert "EnumBody" to complete EnumDeclaration

我无法弄清楚问题是什么。有人可以帮忙吗?

4

2 回答 2

0

在Java中,除非您将该方法的结果存储在字段中,否则您不能在类级别调用方法,而是尝试在类级别调用setDropDownViewResource方法Adapter

class AddContact {
    //...
    Adapter.setDropDownViewResource(...);
}

尝试将此代码移动到构造函数、方法或初始化块。

class AddContact {
    //...

    {//initialization block
        Adapter.setDropDownViewResource(...);
    }
    public AddContact (){//constructor
        Adapter.setDropDownViewResource(...);
    }

    void someMethod(){
        Adapter.setDropDownViewResource(...);
    }
}
于 2013-09-14T02:55:49.560 回答
0

您将代码放在错误的位置,您应该将微调器工作放入其中一种方法中,onCreate或者onStart

只需替换您的课程代码即可

public class AddContact extends Activity {

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


    Spinner spinner = (Spinner) findViewById(R.id.scrollViewMain);   

    ArrayAdapter<CharSequence> Adapter =
            ArrayAdapter.createFromResource(this, R.array.phone_array, android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of
    // choices appears
    spinner.setAdapter(Adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.add_contact, menu);
        return true;
    }

}
于 2013-09-14T02:57:31.487 回答