我希望每当更新或删除任何项目时都更新列表视图。我尝试了很多选项,但它们都没有工作。这是列表视图的代码:
public class HelloBubblesActivity extends Activity {
private com.warting.bubbles.DiscussArrayAdapter adapter;
private ListView lv;
private LoremIpsum ipsum;
private EditText editText1;
private static Random random;
Runnable m_handlerTask;
TextView tv ;
LinearLayout ll;
Handler m_handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discuss);
lv = (ListView) findViewById(R.id.listView1);
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.listitem_discuss);
lv.setAdapter(adapter);
ll = (LinearLayout)findViewById(R.id.wrapper);
m_handler = new Handler();
addItems();
ReduceTimeIteration();
}
public void ReduceTimeIteration()
{
adapter.clear();
((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
lv.invalidate();
lv.requestLayout();
Log.d("Adapter: ", "Adapter is changed");
}
private String addItems() {
String a = "Hello bubbles";
adapter.add(new OneComment(true,a));
return a;
}
}
这是自定义适配器的代码:
public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {
private TextView countryName;
private List<OneComment> countries = new ArrayList<OneComment>();
private LinearLayout wrapper;
static View row ;
@Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public DiscussArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listitem_discuss, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
OneComment coment = getItem(position);
countryName = (TextView) row.findViewById(R.id.comment);
countryName.setText(coment.comment);
countryName.setBackgroundResource(coment.left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
wrapper.setGravity(coment.left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
在列表视图中,我想使用adapter.clear()
删除所有视图,然后想要更新列表视图。但是即使在调用adapter.clear()之后,列表视图仍然保持不变。请帮助我。提前谢谢。
答案 0 :(得分:3)
我建议您按以下方式创建适配器:
// declared in activity
private List<OneComment> countries = new ArrayList<OneComment>();
// in onCreate()
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.listitem_discuss, countries);
然后调用countries.clear(); adapter.notifyDataSetChanged();
清除列表视图。因为您现在基本上使用“国家/地区”(列表)来判断适配器的大小,以及该列表中的哪个项目。