My App Spinner is getting in last

你离开我真会死。 提交于 2019-12-25 07:20:02

问题


hey guys i want to set my spinner default text in top like Select Category but it shown last when i fetch data from data base i want to set this text on top of then items

my code is

 private void loadSpinnerData() {
    SocialDataBase db = new SocialDataBase(getApplicationContext());
    ArrayList<String> lables = db.getAllLabels();
    lables.add("Select Category");
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            R.layout.spinner_text, lables);
    dataAdapter
            .setDropDownViewResource(R.layout.spinner_text);
    txtSpinner.setAdapter(dataAdapter);

}

this is output

[

want to this

please help me


回答1:


Try this line of code

Replace

 lables.add("Select Category"); 

With

 lables.add(0, "Select Category");



回答2:


You are adding your "Select Category" at the last position of the ArrayList. Add it before adding the rest of the items.

private void loadSpinnerData() { 
  SocialDataBase db = new SocialDataBase(getApplicationContext());

  ArrayList<String> lables = new ArrayList<>();
  lables.add("Select Category");
  lables.addAll(db.getAllLabels());

  ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
        R.layout.spinner_tex`enter code here`t, lables);
  dataAdapter.setDropDownViewResource(R.layout.spinner_text);
  txtSpinner.setAdapter(dataAdapter);
} 



回答3:


My friend use this code:

private void loadSpinnerData() {
    SocialDataBase db = new SocialDataBase(getApplicationContext());
    ArrayList<String> lables = new  ArrayList<String>();
    lables.add("Select Category");
    lables.addAll(db.getAllLabels());

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            R.layout.spinner_text, lables);
    dataAdapter
            .setDropDownViewResource(R.layout.spinner_text);
    txtSpinner.setAdapter(dataAdapter);

}

Your are adding "select category" at last index of arraylist that's why it is showing at the end.




回答4:


You can do this in another way!

Step 1 : you can select one item in spinner and upload the value in server.

Step 2 : You can retrieve the selected item from database and load in array adapter or string.

Step 3 : Compare the retrieved item with your stored adapter using if condition. Because in your spinner holds only limited number of array items. So, not more comparison takes if condition.

Step 4 : Do your comparison like the below snippet.

if (getcategory.equals("Speech"))
{
    spn_Category.setSelection(1);
} else if (getcategory.equals("Motivational"))
{
    spn_CategorysetSelection(2);
} else if (getcategory.equals("Dance")) 
{
    spn_Category.setSelection(3);
}

=> Surely the steps will give a idea for you!

Happy coding!



来源:https://stackoverflow.com/questions/38636043/my-app-spinner-is-getting-in-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!