[英]Adding items into a ListView in a fragment
我想通过 editText 在 ListView 中添加项目,但是当我运行我的代码时,它不起作用。
public class EventosFragment extends Fragment {
private ListView lista;
private Button boton;
EditText editText;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_eventos, container, false);
String[] Lista = {};
ListView listView = (ListView) view.findViewById(R.id.Lista);
arrayList = new ArrayList<>(Arrays.asList(Lista));
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(adapter);
editText = (EditText) view.findViewById(R.id.edittxt);
Button btnAdd = (Button) view.findViewById(R.id.Aceptar);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Aceptar = editText.getText().toString();
arrayList.add(Aceptar);
}
});
return view;
}
}
任何建议都可以,我是 Java 的新手,谢谢。
将项目添加到数组列表后,使用适配器的 notifyDataSetChanged() 方法。
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Aceptar = editText.getText().toString();
arrayList.add(Aceptar);
adapter.notifyDataSetChanged();
}
});
希望它会有所帮助!
只需在onclick
方法中添加notifyDataSetChanged
。 您的数据已成功添加到 arraylist 中,但您的适配器不知道您已通知适配器。 像这样
arrayList.add(Aceptar);
//this will notify the adapter whole is changed
adapter.notifyDataSetChanged();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.