使用arrayadapter更新列表视图

时间:2014-02-25 17:10:54

标签: android listview arraylist android-arrayadapter

您正在测试示例gcm应用程序,但每次我发送消息时我都无法在listview中添加其他值。发生的事情是先前的消息被新消息替换。

这是我的代码:

很抱歉编码不好。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_memo);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    list1 = (ListView)findViewById(R.id.listView1);

    registerReceiver(HandleMemoReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));

}
private final BroadcastReceiver HandleMemoReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        //memo.append(newMessage + "\n");
        ArrayList<String> nm = new ArrayList<String>();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(Memo.this,  android.R.layout.simple_list_item_1,nm);
        list1.setAdapter(adapter);
        adapter.add(newMessage);
        adapter.notifyDataSetChanged();
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.memo, menu);
    return true;
}
public void onBackPressed() {
    finish();//go back to the previous Activity
    overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
}

1 个答案:

答案 0 :(得分:2)

您需要使ArrayAdapter成为类级变量 - 此时,每次触发onReceive()方法时都会重新初始化它,这会导致它重置为空ArrayAdapter,然后添加新消息。