我想用两个微调器创建一个应用程序.当您选择第一个微调器中的一个项目时,第二个微调器将仅获得几个项目(取决于所选的项目).
I want to create an application with two Spinners. When you select one of the items inside the first spinner, the second spinner will get only a few items (depends on which item selected).
例如:在第一个微调器中,我选择"Mazda",然后在第二个微调器中,我将只能看到Mazda的模型,而不能看到BMW,Ford等.我可以这样做吗?
For example: in the first spinner I select "Mazda", and then on the second I will be able to see only Mazda's models, not BMW, Ford etc. Can I do something like this?
我试图创建一个没有项目的微调器,并在选择了项时在XML上设置微调器的条目,但是没有方法可以做到这一点.
I tried to create a spinner without items, and set the entries of the spinner on the XML when item selected, but there is no method to do this.
我不创建列表.我想在我的strings.xml中创建string-array资源,并将该数组提供给第二个微调器.
I don't create Lists. I want to create string-array resources in my strings.xml, and give that array to the second spinner.
推荐答案尝试以下代码.我已经在HashMap中组织了示例数据,但是您可以按照自己的方式进行操作.
Try following code. I've organized the sample data in a HashMap but you can do it in your own way.
// hashmap object containing data of spinner1 as 'keys' with relevant // data of spinner2 in List<String> object as 'values' final Map<String, List<String>> data = new HashMap<>(); data.put("A", Arrays.asList("1","2","3","4")); data.put("B", Arrays.asList("4", "5")); data.put("C", Arrays.asList("6", "7", "8", "9")); data.put("D", Arrays.asList("10", "11", "12")); data.put("E", Arrays.asList("13", "14")); // obtaining a string array containing keys(data of spinner1) of above hashmap final String[] dataSpinner1 = new String[data.keySet().size()]; data.keySet().toArray(dataSpinner1); // initializing an string type, ArrayAdapter for spinner1 // you will need to pass activity context, layout for the spinner item and // spinner content(as string array) as arguments to create an array adapter final ArrayAdapter<String> spinner1Adapter = new ArrayAdapter<String>(context, R.layout.spinner_layout, dataSpinner1); spinner1.setAdapter(spinner1Adapter); // setting listner for spinner1 to trigger when an spinner item is being // clicked by the user spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // obtaining relevant data for spinner2 List<String> dataSpinner2 = data.get(dataSpinner1[position]); // crating an setting array adapter for spinner2 ArrayAdapter<String> spinner2Adapter = new ArrayAdapter<String>(context, R.layout.spinner_layout, dataSpinner2); spinner2.setAdapter(spinner2Adapter); } @Override public void onNothingSelected(AdapterView<?> parent) { } });更多推荐
触发其他微调器的微调器
发布评论