我在Android Studio的setAdapter遇到了困难

时间:2016-09-28 18:32:45

标签: android-studio java.lang.class

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.app.Activity;
import java.lang.String;

public class MainActivity extends AppCompatActivity {
    private Spinner spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adminsignup);
        spinner dropdown = (Spinner)findViewById(R.id.selectbranch);
        String[] items = new String[]{"CSE", "EC", "IT","EN","EDT","CIVIL","EE","IND","MECH","MBA","MCA","CLUB"};

        ArrayAdapter<String> adapter = new ArrayAdapter< >(this, android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);    
    }   
}

错误在.setAdapter时出现红色。我尝试了所有可能的方法,甚至尝试将this更改为this.getActivity(),但无济于事。

1 个答案:

答案 0 :(得分:0)

实际上,错误就在这一行:

spinner dropdown = (Spinner)findViewById(R.id.selectbranch);

因为您尝试声明“spinner”类型的“dropdown”变量,并且没有“spinner”类。有两种解决方案,一种是将变量下拉列表声明为Spinner类型,如下所示:

Spinner dropdown = (Spinner)findViewById(R.id.selectbranch);

或者,您可以使用在MainActivity类开头声明的私有变量“spinner”,然后代码应如下所示:

    spinner = (Spinner)findViewById(R.id.selectbranch);
    String[] items = new String[]{"CSE", "EC", "IT","EN","EDT","CIVIL","EE","IND","MECH","MBA","MCA","CLUB"};

    ArrayAdapter<String> adapter = new ArrayAdapter< >(this, android.R.layout.simple_spinner_dropdown_item, items);
    spinner.setAdapter(adapter);

两种解决方案都可以使用,但如果您计划稍后在代码中使用此适配器,则更好地选择私有变量。 此外,使用{}定义数组时,不需要使用“new String []”,也不需要使用“&lt;&gt;”在“new ArrayAdapter”之后。