Here's how I would do it.
In the main activity layout file, I'd put 2 EditText fields with ids nameEditText
and ageEditText
in the layout, below the listView
, as well as a button to save. In your button, do not forget to add the line:
android:click="onSave"
and in your Main Activity, create a function as such:
public void onSave(View view){
//this is the function that will activate when you click your button
}
It also goes without saying that you should hook up your EditTexts as such:
public class MainActivity extends Activity {
//DO NOT DECLARE THIS AS STATIC, OTHERWISE YOU WON'T BE ABLE TO ADD TO IT
ArrayList<NameAndAgeClass> nameAndAgeList = new ArrayList<NameAndAgeClass>();
EditText nameInput;
EditText ageInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aa);
//hook up your EditText as such:
nameInput = (EditText) findViewById(R.id.nameEditText);
ageInput = (EditText) findViewById(R.id.ageEditText);
//more of your code here...
}
//more of your code here, and the onSave function
}
What we want to do is when you click this "Save" button, we will take the input from the editText which we initialized in the onCreate
function and add it to our ArrayList. Here's how we'll do it.
public void onSave(View view){
//we get the string values from the EditText input
Sting nameInputFromField = nameInput.getText().toString();
Sting ageInputFromField = ageInput.getText().toString();
//we create a class using our values
NameAndAgeClass entry = new NameAndAgeClass(nameInputFromField, ageInputFromField);
//then we add it to our ArrayList
nameAndAgeList.add(entry);
//after that, we get the customListViewAdapter (I trust that you have this one)
//and call a neat function
//the function is called something like that
nameAndAgeAdapter.notifyDataSetChanged();
}
What notifyDataSetChanged
does is that it "refreshes" your listView. Usually this is done after modifications are made in the ListViews Data so that the changes would be seen by the user right away.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…