简体   繁体   English

如何将项目添加到微调器?

[英]How to add items to a spinner?

I have a spinner that is populated with a JSON object, but I want to add one item to the spinner manually in the first position saying "select one" kind of a title to the spinner , how do I do that? 我有一个填充了一个微调JSON对象,但我想一个项目在第一位置手动添加到飞旋说:“选择一个”之类的标题到的spinner ,我该怎么做呢? heres my code 这是我的代码

ArrayList<Empresa> Companhias = new ArrayList<Empresa>();                   
        try {

        JSONObject mainJson = new JSONObject(new String(buffer));



            JSONArray jsonArray = mainJson.getJSONArray("GetCompaniesResult");
            Log.i("mainjson234","" +  jsonArray);

            for (int i = 0; i < jsonArray.length(); i++) {

               JSONObject objJson = jsonArray.getJSONObject(i);

                int id = objJson.getInt("CompanyID");
                String name =objJson.getString("CompanyName"); 


                Empresa empresa = new Empresa();
                empresa.setId(id);
                empresa.setCompanyName(name);
                Companhias.add(empresa);


                Log.i("empresas", "" + empresa.toString());


            }



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

                mySpinner.setAdapter(new ArrayAdapter<Empresa>(this, android.R.layout.simple_spinner_dropdown_item,  Companhias));

                 spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
    Empresa empresa = new Empresa();
            empresa.setId(0);
            empresa.setCompanyName("name");
            Companhias.add(empresa);

add these lines before your for loop 在您的for循环之前添加这些行

for (int i = 0; i < jsonArray.length(); i++) {

           JSONObject objJson = jsonArray.getJSONObject(i);

            int id = objJson.getInt("CompanyID");
            String name =objJson.getString("CompanyName"); 


            Empresa empresa = new Empresa();
            empresa.setId(id);
            empresa.setCompanyName(name);
            Companhias.add(empresa);


            Log.i("empresas", "" + empresa.toString());


        }

Add the first four lines in your code before for loop. 在循环之前,在代码中添加前四行。 And make a correction in for loop as under. 并在下面的for循环中进行更正。

Empresa empresa = new Empresa();
        empresa.setId(0);
        empresa.setCompanyName("name");
        Companhias.add(empresa);

for (int i = 0; i < jsonArray.length(); i++) {

       JSONObject objJson = jsonArray.getJSONObject(i);

        int id = objJson.getInt("CompanyID");
        String name =objJson.getString("CompanyName"); 

        empresa.setId(id);
        empresa.setCompanyName(name);
        Companhias.add(empresa);


        Log.i("empresas", "" + empresa.toString());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM