Java无法识别ListView变量

时间:2017-07-05 01:12:03

标签: java android listview

我尝试在AndroidStudio中创建一个值为" nome"的ListView。我为此创建了一个列表和一个适配器,但我的应用程序无法识别变量" services"。

这是我的活动代码

public class MainActivity extends AppCompatActivity {
    private String service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.list_item1);


        ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services); <-- in this line
        listView.setAdapter(servicesAdapter);

    }


    private List<Services> gerarServices(){
        List<Services> services  = new ArrayList<Services>();
        services.add(criarServices("Home"));
        services.add(criarServices("Delivery"));

        return services;
    }

    private Services criarServices(String nome){
        Services service = new Services(nome);
        return service;
    }
}

有什么建议吗?提前谢谢!

2 个答案:

答案 0 :(得分:3)

services变量不在onCreate方法的范围内。正如@ Code-Apprentice所提到的,您可能想要了解有关局部变量范围的更多信息。

因此,您可能想要做的是在gerarServices()方法中调用onCreate方法并将其分配给本地变量,然后将其传递给ArrayAdapter。像这样:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.list_item1);

    List<Services> services = gerarServices();


    ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);
    listView.setAdapter(servicesAdapter);

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.list_item1);


    ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, gerarServices());
    listView.setAdapter(servicesAdapter);

}

希望它有所帮助!

答案 1 :(得分:1)

在您的代码中,我没有看到任何声明和初始化services的方法 但gerarServices()会返回Services列表。所以我想你必须在使用任何变量或类实例之前做上述操作 像这样,

ListView listView = (ListView) findViewById(R.id.list_item1);

// Add this line of code
List<Services> services = gerarServices();

ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);

希望得到这个帮助。