简体   繁体   English

Android Spinner-防止刷新后关闭

[英]Android Spinner - prevent close after refresh

I have a dropdown spinner that shows a list of items, and this list updates every X seconds after receiving a response from the API. 我有一个下拉菜单,显示项目列表,并且在收到API的响应后,此列表每隔X秒更新一次。

The problem is that when the list updates, the spinner automatically closes. 问题是,当列表更新时,微调框将自动关闭。 I want it to remain opened after the refresh. 我希望它在刷新后保持打开状态。

private void getItems(JSONArray j){
   ArrayList<String> items = new ArrayList<>();

   for (int i=0; i < j.length(); i++){
       try {
           //Getting json object
           JSONObject json = j.getJSONObject(i);

           //Adding the name of the student to array list
           items.add(json.getString("name"));
       } catch (JSONException e) {
           e.printStackTrace();
       }
   }
   spinner.setAdapter(new ArrayAdapter<>(BaseActivity.this, android.R.layout.simple_spinner_dropdown_item, items));
}

This is a demo that shows how you can update the Spinner while keeping it open. 这是一个演示,展示了如何在保持打开状态的同时更新Spinner

First initialize the Spinner by setting the adapter using setAdapter . 首先通过使用setAdapter设置adapter来初始化Spinner

Then an update comes for the items. 然后,将对这些项目进行更新。 I used a Handler to mimic the update. 我使用Handler来模拟更新。 Inside the getItems method instead of creating a new adapter (as you have done) use notifyDataSetChanged to notify the adapter that the dataset has changed. getItems方法内,而不是创建新适配器(如您所完成的),请使用notifyDataSetChanged来通知适配器数据集已更改。

Code below. 下面的代码。

private Spinner spinner;
private ArrayAdapter<String> adapter;
final List<String> items = new ArrayList<>();

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

    initializeSpinner();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            try {
                String updatedItems = "[{\"name\" : \"test1\"}, {\"name\" : \"test2\"}, {\"name\" : \"test2\"}]";
                getItems(new JSONArray(updatedItems));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, 10000);

}


private void initializeSpinner() {
    items.add("initial");

    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(TestActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
    spinner.setAdapter(adapter);
}

private void getItems(JSONArray j) {
    for (int i = 0; i < j.length(); i++) {
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            items.add(json.getString("name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    adapter.notifyDataSetChanged();
}

Actually, you just need to initialize and add the adapter to the spinner first. 实际上,您只需要先初始化适配器并将其添加到微调器即可。 Then you load your data, add the data to the adapter and call adapter.notifyDataSetChanged(); 然后,加载数据,将数据添加到适配器并调用adapter.notifyDataSetChanged();。

Here is my test activity, you can copy paste it directly to your activity 这是我的测试活动,您可以将其直接复制粘贴到您的活动中

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    setContentView(linearLayout);

    Spinner spinner = new Spinner(this);
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>());
    spinner.setAdapter(adapter);

    Button button = new Button(this);
    button.setText("load data");
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TestActivity.this.getWindow().getDecorView().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadData();
                }
            }, 2000);
        }
    });

    linearLayout.addView(spinner);
    linearLayout.addView(button);
}

private void loadData() {
    String jsonArray = "[\n" +
            "  {\n" +
            "    \"id\": \"1\",\n" +
            "    \"name\": \"dada1\"\n" +
            "  },\n" +
            "  {\n" +
            "    \"id\": \"2\",\n" +
            "    \"name\": \"dada2\"\n" +
            "  },\n" +
            "  {\n" +
            "    \"id\": \"3\",\n" +
            "    \"name\": \"dada3\"\n" +
            "  },\n" +
            "  {\n" +
            "    \"id\": \"4\",\n" +
            "    \"name\": \"dada4\"\n" +
            "  },\n" +
            "  \n" +
            "]";
    try {
        getItems(new JSONArray(jsonArray));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private ArrayAdapter<String> adapter;

private void getItems(JSONArray j) {
    ArrayList<String> items = new ArrayList<>();

    for (int i = 0; i < j.length(); i++) {
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            items.add(json.getString("name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    adapter.addAll(items);
    adapter.notifyDataSetChanged();
}

How to test it? 如何测试呢?

  • Run the activity 运行活动
  • Press the button 按下按钮
  • After 2 seconds your items is generated 2秒后,您的物品生成
  • Press the button again and press the spinner immediately 再次按下按钮,然后立即按下微调器
  • You will see that the items is added without closing the popup after 2 seconds 您将看到2秒钟后添加了项目但没有关闭弹出窗口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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