【问题标题】:Updating listview with arrayadapter [duplicate]使用 arrayadapter 更新列表视图 [重复]
【发布时间】:2014-02-25 17:10:54
【问题描述】:

您好,正在测试一个示例 gcm 应用程序,但每次我发送消息时,我都无法在列表视图中添加另一个值。发生的情况是之前的消息正在被新消息替换。

这是我的代码:

抱歉编码不佳。

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);
}

【问题讨论】:

    标签: android listview arraylist android-arrayadapter


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 2014-07-15
      相关资源
      最近更新 更多