如何解决为什么从 ArrayAdapter 中的 ListView 获取项目时会出现错误?
我为 ListView 创建了一个 ArrayAdapter,并使用 ArrayList
类 ListViewAdapter
public class ListViewAdapter extends ArrayAdapter
{
ArrayList<HashMap<Object,Object>> items;
public ListViewAdapter(Context context,ArrayList<HashMap<Object,Object>> items)
{
super(context,R.xml.chat,items);
this.items = items;
}
@Override
public View getView(int position,View view,ViewGroup parent)
{
if (view == null)
{
view = LayoutInflater.from(getContext()).inflate(R.xml.chat,parent,false);
}
TextView text_name = view.findViewById(R.id.text_name);
TextView text_message = view.findViewById(R.id.text_message);
text_message.setText(items.get(position).get("msg").toString());
return view;
}
}
MainAcrivity:
public class MainActivity extends Activity
{
public static ListView list_chat;
public static EditText edit_message;
public static Button button_send;
public static ArrayList<HashMap<Object,Object>> list_map = new ArrayList<>();
public static HashMap<Object,Object> user_map;
public static HashMap<Object,Object> chat_map;
public static HashMap<Object,Object> send_map;
public static LayoutInflater inflaterChat;
public static String BUILD;
public static Texture texture;
public static ListViewAdapter chatAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list_chat = findViewById(R.id.list_chat);
edit_message = findViewById(R.id.edit_message);
button_send = findViewById(R.id.button_send);
BUILD = Build.ID.replace(".","");
chatAdapter = new ListViewAdapter(this,list_map);
list_chat.setAdapter(chatAdapter);
button_send.setonClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
chat_map = new HashMap<>();
chat_map.put("msg",edit_message.getText());
list_map.add(chat_map);
chatAdapter.notifyDataSetChanged();
}
});
}
}
解决方法
我发现了错误,我将“getText()”放入一个HashMap值中,当更新ListView时,它没有获取已经定义的值,而是再次执行getText()命令例如:将字符串设置为“。 getText ()" 而不是 "HashMap " 我的解决方案是获取字符串中的文本,然后使用该字符串设置 HashMap 的值
HashMap<Object,Object> chat_map = new HashMap<>();
String message = String.valueOf(edit_message.getText());
chat_map.put("msg",message);
list_chat_map.add(chat_map);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。