简体   繁体   中英

Recycler View on Spinner Item

Project Goal is the following. Spinner shows 4 items...Men Women Kids Cars and you select Men then Recycler View appears and displays men names and then u click another item in spinner like Cars then the same Recycler View to display Car names. So each spinner item will call the Recycler View that will display info according to what item you selected in spinner.

//Spinner code
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner spinner = findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);


    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        String text = adapterView.getItemAtPosition(i).toString();
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        if (i==1){
            Toast.makeText(this, "stathis tocks", Toast.LENGTH_SHORT).show();
        }
    }

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

    }
}

//Recycler View sample code
public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;//Bridge between data and image/ arrayList and RecyclerView
    private RecyclerView.LayoutManager mLayoutManager;//align single items in our list

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<ExampleItem> exampleList = new ArrayList<>();
        exampleList.add(new ExampleItem("Line 1", "Line 2"));
        exampleList.add(new ExampleItem("Line 3", "Line 4"));
        exampleList.add(new ExampleItem( "Line 5", "Line 6"));
        exampleList.add(new ExampleItem("Line 7", "Line 8"));
        exampleList.add(new ExampleItem( "Line 9", "Line 10"));
        exampleList.add(new ExampleItem("Line 11", "Line 12"));
        exampleList.add(new ExampleItem("Line 13", "Line 14"));
        exampleList.add(new ExampleItem("Line 15", "Line 16"));
        exampleList.add(new ExampleItem("Line 17", "Line 18"));
        exampleList.add(new ExampleItem("Line 19", "Line 20"));
        exampleList.add(new ExampleItem("Line 21", "Line 22"));
        exampleList.add(new ExampleItem("Line 23", "Line 24"));
        exampleList.add(new ExampleItem("Line 25", "Line 26"));
        exampleList.add(new ExampleItem("Line 27", "Line 28"));
        exampleList.add(new ExampleItem("Line 29", "Line 30"));
        exampleList.add(new ExampleItem("Line 1", "Line 2"));
        exampleList.add(new ExampleItem("Line 3", "Line 4"));
        exampleList.add(new ExampleItem( "Line 5", "Line 6"));
        exampleList.add(new ExampleItem("Line 7", "Line 8"));
        exampleList.add(new ExampleItem( "Line 9", "Line 10"));
        exampleList.add(new ExampleItem("Line 11", "Line 12"));
        exampleList.add(new ExampleItem("Line 13", "Line 14"));
        exampleList.add(new ExampleItem("Line 15", "Line 16"));
        exampleList.add(new ExampleItem("Line 17", "Line 18"));
        exampleList.add(new ExampleItem("Line 19", "Line 20"));
        exampleList.add(new ExampleItem("Line 21", "Line 22"));
        exampleList.add(new ExampleItem("Line 23", "Line 24"));
        exampleList.add(new ExampleItem("Line 25", "Line 26"));
        exampleList.add(new ExampleItem("Line 27", "Line 28"));
        exampleList.add(new ExampleItem("Line 29", "Line 30"));
        exampleList.add(new ExampleItem("Line 1", "Line 2"));
        exampleList.add(new ExampleItem("Line 3", "Line 4"));
        exampleList.add(new ExampleItem( "Line 5", "Line 6"));
        exampleList.add(new ExampleItem("Line 70", "Line 8"));
        exampleList.add(new ExampleItem( "Line 9", "Line 10"));
        exampleList.add(new ExampleItem("Line 11", "Line 12"));
        exampleList.add(new ExampleItem("Line 13", "Line 14"));
        exampleList.add(new ExampleItem("Line 105", "Line 16"));
        exampleList.add(new ExampleItem("Line 17", "Line 18"));
        exampleList.add(new ExampleItem("Line 109", "Line 20"));
        exampleList.add(new ExampleItem("Line 21", "Line 22"));
        exampleList.add(new ExampleItem("Line 23", "Line 24"));
        exampleList.add(new ExampleItem("Line 2445", "Line 26"));
        exampleList.add(new ExampleItem("Line 27", "Line 280"));
        exampleList.add(new ExampleItem("Line 29", "Line 300"));

        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new ExampleAdapter(exampleList);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }
}

//Current code i want merge the ones on top

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;//Bridge between data and image/ arrayList and RecyclerView
    private RecyclerView.LayoutManager mLayoutManager;  // align single items in our list



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

        //RecycleView
        ArrayList<ExampleItem> exampleList = new ArrayList<>();
        for(int i=0;i<50;i++){
            String tmp="Text: "+i;
            String tmp2="Text: "+(i+1);
            exampleList.add(new ExampleItem(tmp, tmp2));
        }

        //Recycle View
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new ExampleAdapter(exampleList);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        String text = adapterView.getItemAtPosition(i).toString();
        Toast.makeText(adapterView.getContext(), text, Toast.LENGTH_SHORT);
        Log.d("TAG", String.valueOf(i));

        if(i==0){
            //RecycleView
            ArrayList<ExampleItem> exampleList = new ArrayList<>();
            for(int j=0;j<50;i++){
                String tmp="Text: "+j;
                String tmp2="Text: "+(j+1);
                exampleList.add(new ExampleItem(tmp, tmp2));
            }

            //mRecyclerView = findViewById(R.id.recyclerView);
            //mRecyclerView.setHasFixedSize(true);
           // mLayoutManager = new LinearLayoutManager(this);
            mAdapter = new ExampleAdapter(exampleList);
            //mRecyclerView.setLayoutManager(mLayoutManager);
           // mRecyclerView.setAdapter(mAdapter);
        }
        if(i==1){

        }
        if(i==2){

        }
    }

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

    }
}

I don't know how you are saving your data and retrieving but I have made this type of program in my project so I can give you my example based on which you can create your own. Okay. I had been creating an ecommerce app in which I need to show sub category names in the second spinner based on category name selected in the first spinner. So what I did was that I created a table with all category names and a second table containing all subcategory name column as well as their corresponding category names in the second column.

Now, I passed the category selected in the first spinner as map and fetched the all subcategories where category name was the corresponding selected category.

This is called dependent spinner.

codes are below

Java method for fetching data from MySQL based on the first spinner

 public void getSubCategory(){
    final String genderText = gender ;
    final String categoryText = category ;
    ArrayList<String> subCateg = new ArrayList<>();

    StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

    if(response.trim().equalsIgnoreCase("No subCategory added")) {
    subCateg.add("No sub category");
    myAdapter3 = new ArrayAdapter<String>(addProductPage.this, R.layout.droptextlayout, subCateg);
    myAdapter3.notifyDataSetChanged();
    subCategoryDrop.setAdapter(myAdapter3);
    }else {
        try {
            JSONObject Jobject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
            String success = Jobject.getString("success");
            JSONArray Jarray = Jobject.getJSONArray("datas");

            if (success.equals("1")) {
                for (int i = 0; i < Jarray.length(); i++) {
                    JSONObject object = Jarray.getJSONObject(i);
                    String name = object.getString("name");

                    subCateg.add(name);
                }

                myAdapter3 = new ArrayAdapter<String>(addProductPage.this, R.layout.droptextlayout, subCateg);
                myAdapter3.notifyDataSetChanged();
                subCategoryDrop.setAdapter(myAdapter3);
            }

        } catch (JSONException jsonException) {
            jsonException.printStackTrace();
        }
    }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<String, String>();
            System.out.println(categoryText);
            map.put("category", categoryText);
            map.put("gender", genderText);

            return map;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
    queue.add(request);
};

I am fetching all sub categories based on two property gender and category.

PHP code is here...

<?php
include "config.php";

 $gender = $_POST['gender'];
$category = $_POST['category'];


   $sql="SELECT * FROM `$db`.`subCategory` WHERE `category`= '{$category}' 
   AND `gender`='{$gender}'";
   $result=mysqli_query($conn,$sql);
   $categories['datas'] = array();
   if(mysqli_num_rows($result)>0){
       while($row=mysqli_fetch_array($result)){
           $data['id']=$row['0'];
        $data['name']= $row['1'];
        $data['gender']=$row['2'];
        $data['image']=$row['3'];

        array_push($categories['datas'],$data);
       }

       $categories['success']='1';
       echo json_encode($categories);
        mysqli_close($conn);
    }else{ 
        echo "No subCategory added";

    }

?>

Always remember if you are fetching data from server into the spinner always put your adapter and set adapter inside that method which is fetching data from the server otherwise spinner will not show the selected item in the layout.

If there is any confusion or doubt kindly ask me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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