我正在编写一个简单的联系人列表应用程序,它允许用户输入姓名和姓氏,将这些项目存储在列表中,并将它们显示为 editText 字段下方的列表。我创建了一个具有名字和姓氏两个字段的对象,并尝试将对象添加到列表以显示在按钮下方。但是,屏幕上什么也没有出现。调试消息显示对象已成功创建并添加到列表中,但我尝试显示对象字段值的方式一定有问题。如果有人能告诉我我在这里做错了什么,我将不胜感激。
这是布局 xml 代码(ListView 部分):
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView1"
android:layout_marginTop="20dp"/>
Java部分:
public class Person {
private static String firstname;
private static String lastname;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public static String getFirstname() {
return firstname;
}
public static String getLastname() {
return lastname;
}
public String toString(){
return getFirstname()+ " " + getLastname();
}
}
和主要功能
public class MainActivity extends AppCompatActivity {
private EditText ent_name;
private EditText ent_surname;
private ListView listView;
private Person person;
private String first_name;
private String last_name;
private ArrayAdapter<Person> adapter;
private List<Person> people = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ent_name = findViewById(R.id.txt_firstName);
ent_surname = findViewById(R.id.txt_lastName);
listView = findViewById(R.id.listView1);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, people);
listView.setAdapter(adapter);
}
public void clear(View view) {
ent_name.setText("");
ent_surname.setText("");
}
public void add(View view) {
first_name = ent_name.getText().toString();
last_name = ent_surname.getText().toString();
Person person = new Person(first_name, last_name);
people = Arrays.asList(person);
adapter.notifyDataSetChanged();
}
紫衣仙女
相关分类