我的微调器setOnItemSelectedListener无法正常工作

时间:2018-08-02 09:50:12

标签: android

这是我的代码。当我从下拉列表中选择一个项目时,该项目不会显示在微调器上。另外,onItemSelected()无法运行。

final String[] productBrand = new String[1];
        //Spinner
        ArrayList<String> brandList = getBrandsFromFirebase();
        sp_productBrand = findViewById(R.id.sp_productBrand);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, brandList);
        // Specify the layout to use when the list of choices appears
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        sp_productBrand.setAdapter(adapter2);

        sp_productBrand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                productBrand[0] = (String) adapterView.getItemAtPosition(i);
                Log.i(TAG,"ITEM SELECTED "+productBrand[0]);

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

***如果我使用资源文件中的列表,那么它可以很好地工作(选定的项目显示在微调器上,onItemSelected()也很好)

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

我的资源字符串就是这个

<string-array name="brand">
        <item>Technic</item>
        <item>Revuele</item>
        <item>Beauty Formulas</item>
        <item>Vasline</item>
        <item>Revlon</item>
        <item>Sleek</item>
        <item>Xpel</item>
        <item>Mother Care</item>
        <item>Revolution</item>
        <item>NYX</item>
        <item>Astral</item>
        <item>Dove</item>
        <item>The Body Shop</item>
        <item>Tresemme</item>
        <item>Herbal Essences</item>
        <item>Loreal</item>
        <item>Rimmel</item>
        <item>NSPA</item>
        <item>Victorias Secret</item>
        <item>Others</item>
    </string-array>

这是我的getBrandFromFirebas()方法

private ArrayList<String> getBrandsFromFirebase(){

        final ArrayList<String> brandList = new ArrayList<String>();

        DatabaseReference mDB2 = FirebaseDatabase.getInstance().getReference("BRAND");

        mDB2.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    brandList.add(ds.getKey());
                    Log.i(TAG,"Spinner : "+ds.getKey());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        return brandList;

    }

0 个答案:

没有答案