当我从listview活动中打开一个新活动然后返回listview活动或者如果我重新打开相同的listview活动时,我的listview项目会重复出现。
public class PlaylistAdapter extends ArrayAdapter<PlaylistBean> {
Context context;
private LayoutInflater inflater;
public static class ViewHolder
{
public final TextView name;
public final ImageView image;
public ViewHolder(View view)
{
name = (TextView) view.findViewById(R.id.namePlaylist);
image = (ImageView) view.findViewById(R.id.imagePlaylist);
}
}
public PlaylistAdapter(Context context, List<PlaylistBean> items)
{
super(context, R.layout.row_layout_playlist, items);
inflater = LayoutInflater.from(context);
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent)
{
View view = convertView;
if (view == null)
{
LayoutInflater vi = LayoutInflater.from(getContext());
view = vi.inflate(R.layout.row_layout_playlist, null);
}
final ViewHolder viewHolder = new ViewHolder(view);
PlaylistBean playlistBean = getItem(position);
viewHolder.name.setText(playlistBean.getName());
viewHolder.image.setImageResource(playlistBean.getImage());
return view;
}
}
这是我的PlaylistBean类
的代码public class PlaylistBean implements Serializable {
private int image;
private String name;
public PlaylistBean(int image, String name)
{
this.image = image;
this.name = name;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
以下是我的主要活动的代码
公共类播放列表扩展了AppCompatActivity {
public static List<PlaylistBean> items = new ArrayList<>();
ArrayAdapter<PlaylistBean> myArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
playlistListView = (ListView) findViewById(R.id.playlistListView);
myArrayAdapter = new PlaylistAdapter(Playlist.this, items);
playlistListView.setAdapter(myArrayAdapter);
createData();
}
public void createData()
{
PlaylistBean bean1 = new PlaylistBean(R.drawable.popular_upload, "Popular Uploads");
items.add(bean1);
}
}
答案 0 :(得分:2)
当您的活动转到后台时,您可以使用以下代码清除列表视图:
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
yourListView.setListAdapter(null); //This clears the listview items
}
答案 1 :(得分:0)
这就是发生的事情。
List<PlaylistBean> items
是静态的。ListView
ListView
变为空,因为items.size()
为0 createData()
方法调用哪个填充列表。如何过来这个。
我希望你想在第一次运行时在列表视图中显示一些内容,并希望保留items
列表static
@Override
protected void onCreate(Bundle sis){
super.onCreate(sis);
setContentView(R.layout.activity_playlist);
playlistListView = (ListView) findViewById(R.id.playlistListView);
//fill the list here.
createData();
myArrayAdapter = new PlaylistAdapter(Playlist.this, items);
playlistListView.setAdapter(myArrayAdapter);
}
然后更改您的createData()
方法。
public static void createData(){
//instatiate the list items here
items=new ArrayList<>();
PlaylistBean bean1 = new PlaylistBean(R.drawable.popular_upload, "Popular Uploads");
items.add(bean1);
}