如何从参数向ListView添加元素

时间:2018-11-13 05:54:16

标签: java android list arraylist

我正在尝试添加传递给参数的元素,可以说我需要在列表中添加10个元素,所以我需要10个.add,所以我想这样做是为了能够加载不同的微调器用同样的方法,这就是我做得太过分了

 private void setSpinnerData(Spinner spinner){
        List<String> spinnerArray =  new ArrayList<String>();
        spinnerArray.add("item1");
        spinnerArray.add("item2");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, spinnerArray);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
    }

我需要的是这样的

 private void setSpinnerData(Spinner spinner,int elementsToAdd){
        List<String> spinnerArray =  new ArrayList<String>();
        for(int i = 0 ; i<elementsToAdd;i++){
        spinnerArray.add(i);
       }


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, spinnerArray);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
    }

但是我需要定义要添加的每个元素,我该怎么做?

1 个答案:

答案 0 :(得分:1)

我想这就是您想要的:

["yahoo!",["yahoo mail","yahoo finance","yahoo news","yahoo mail login","yahoo sports","yahoo fantasy football","yahoo fantasy","yahoo india","yahoo groups","yahoo search"]]

 string json = Helpers.GetGoogleSuggestionKeyword("Yahoo!").ToString();
            JArray GoogleSuggesionKeywordResult = JArray.Parse(json);
            foreach (JObject item in GoogleSuggesionKeywordResult)
            {
            //    MessageBox.Show(item.ToString());
            }

或者如果您需要传递ArrayList:

private void setSpinnerData(Spinner spinner,String... params){
        List<String> spinnerArray =  new ArrayList<String>();

        for(String str:params){
            spinnerArray.add(str);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, spinnerArray);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
}