[英]How adding an item in the ArrayList and ArrayAdpter
I'm doing a chat and I need to increment a list with the messages sent though I am unable to do. 我正在聊天,虽然无法执行,但我需要增加发送邮件的列表。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_janela);
ArrayList<String> mensagens = new ArrayList<String>();
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mensagens);
ListView lv = (ListView)findViewById(R.id.lista);
lv.setAdapter(adapter);
}
This method below I get the message text and is where I wanted to increase the list. 我在下面的此方法中获取消息文本,这是我想要增加列表的位置。
private void escreve(String texto) {
mensagens.add(texto);
}
I hope it has become clear , thanks for attention 我希望情况已经清楚了,谢谢关注
Declare both arralist and adapter outside and then just notify when data changed so it will work, check below solution. 声明外部的arralist和适配器,然后仅在数据更改时通知它以便起作用,请检查以下解决方案。
ArrayList<String> mensagens;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_janela);
mensagens = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mensagens);
ListView lv = (ListView)findViewById(R.id.lista);
lv.setAdapter(adapter);
}
private void escreve(String texto) {
mensagens.add(texto);
adapter.notifyDataSetChanged();
}
Your error: You cannot create a list as local variable in one method and use it in another. 您的错误:您无法在一种方法中将列表创建为局部变量,而在另一种方法中使用它。 You have to make mensages
a class variable. 您必须将mensages
类变量。
If I understand correctly, you need a member variable. 如果我理解正确,则需要一个成员变量。
And you can add to an ArrayAdapter directly without needing to notifyDatasetChanged 而且您可以直接添加到ArrayAdapter而不需要notifyDatasetChanged
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_janela);
ArrayList<String> mensagens = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mensagens);
...
private void escreve(String texto) {
adapter.add(texto);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.