尝试在android中实现微调器时出现奇怪的错误

时间:2013-09-14 02:48:32

标签: java android spinner

我正在尝试在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);
}

当我写作&#34; Adapter.setDropDownViewResource ....&#34;我得到了这个奇怪的错误,这是堆栈跟踪:

 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

我无法确定问题所在。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

在Java中,您无法在类级别调用方法,除非您将该方法的结果存储在字段中,但是尝试在类级setDropDownViewResource上调用Adapter方法

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

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

class AddContact {
    //...

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

    void someMethod(){
        Adapter.setDropDownViewResource(...);
    }
}

答案 1 :(得分:0)

您将代码放在错误的位置,您应该将微调器工作放入方法之一 onCreateonStart

只需替换它可以使用的类代码

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

}