I have a Save button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/save"
android:layout_below="@+id/editText"
android:background="@android:color/holo_blue_light"
android:textColor="@android:color/white"
android:textSize="20dp"
android:onClick="saveEvent"/>
And when it is pressed, I want it to add the EditText input to a Listview. The the Listview and EditText+Save Button elements are on different XML layouts, by the way.
I have an activity called SaveEvent, that happens when the Save button is pressed. How do I make it add the EditText input to the ListView element?
Thank you so much.
A piece of MakeEvent.java:
public void saveEvent(View view) {
Intent intent = new Intent(this, SaveEvent.class);
startActivity(intent);
}
SaveEvent.java:
package com.kass.planner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class SaveEvent extends Activity implements View.OnClickListener{
private Button btn;
private EditText et;
private ListView lv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.save);
btn.setOnClickListener(this);
et = (EditText) findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
lv = (ListView) findViewById(R.id.event_list);
lv.setAdapter(adapter);
}
public void onClick(View v) {
String input = et.getText().toString();
if (input.length() > 0) {
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
}
But this code doesn't work... ^ Thank you.
upon enlightenment from cricket guy and revisiting some of my old programs instead of updating the adapter object
only update the underlining data and call the following method to Bind the list view object with the updated adapter object
public void fillList() {
ArrayAdapter<String> adapter= new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,getItems());
lv.setAdapter(adapter);
}
I Agree. not memory efficient but it works well
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.