点击Spinner
项目将新数据添加到RecyclerView
而不删除旧数据。
比如,我在 Spinner 中有two
件商品:Appliances
和Accessories
。
默认情况下,我将Appliances
数据显示在 RecyclerView 中,但每当我在附件上tap
时 - 它显示{{1进入 RecyclerView ,但Accessories data
,而我期待只有below Appliances data
数据进入RecyclerView
MainActivity.java:
Accessories
CategoryAdapter.java:
public class MainActivity extends AppCompatActivity {
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_screen);
.........
stringList = new ArrayList<String>();
stringList.add("Appliances");
stringList.add("Accessories");
ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,
stringList);
spinnerMenu.setAdapter(stringArrayAdapter);
......
initializeAdapter();
.....
spinnerMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
presenter.loadAppliances();
break;
case 1:
presenter.loadAccessories();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
.......
}
public void initializeAdapter() {
categoryAdapter = new CategoryAdapter(this, new ArrayList<Category>());
mRecyclerView.setAdapter(categoryAdapter);
}
public void addMenu(List<Category> posts) {
categoryAdapter.addAllData(posts);
categoryAdapter.notifyDataSetChanged();
}
}
答案 0 :(得分:2)
首先清除旧的ArrayList,然后将数据添加到Arraylist中。
public void addMenu(List<Category> posts) {
categoryAdapter.addAllData(posts);
categoryAdapter.notifyDataSetChanged();
}
public void addAllData(List<Categories> posts) {
this.posts.clear();
this.posts.addAll(posts);
}
答案 1 :(得分:0)
选择项目时需要重置适配器。所以试试这个:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
initializeAdapter();
//after this the switch case
我还建议你有办法知道微调菜单位置。
在第一个menupresenter.loadAppliances();
有int positionSelected = 0;
然后在开关案例中,
switch position
case: 0
if(positionSelected != 0) {
initializeAdapter();
menupresenter.loadAppliances();
positionSelected = 0;
}...
case: 1
if(positionSelected != 1) {
initializeAdapter();
menupresenter.loadAccessories();
positionSelected = 1;
}...
这将确保您不会不必要地重置recyclerView适配器。就像显示appliaces数据和用户一样,在下拉列表中再次选择设备