简体   繁体   中英

Adding items into a ListView in a fragment

I want to add items in ListView through an editText, but when i run my code, it dosn't work.

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

Any suggestions will do, i'm new in Java, thanks.

Use notifyDataSetChanged() method of adapter after adding item to arraylist.

btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String Aceptar = editText.getText().toString();
            arrayList.add(Aceptar);
            adapter.notifyDataSetChanged();
        }
    });

Hope it will help!!

Just add notifyDataSetChanged in onclick method. Your data is successfully added in arraylist but your adapter doesn't know about it you have notify the adapter. Just like this

 arrayList.add(Aceptar);
 //this will notify the adapter whole is changed
 adapter.notifyDataSetChanged();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM