【发布时间】:2017-11-16 09:17:19
【问题描述】:
在我的主要活动中,有两个编辑文本,一个用于学生姓名,一个用于学生学院,还有一个添加学生按钮,如下代码所示,添加学生按钮的 onClick 函数将插入编辑文本的值到列表视图:
public class Students extends AppCompatActivity {
//Initializing ...
EditText NameEditText;
EditText CollegeEditText;
Button AddButton;
ListView StudentListView;
ArrayList<Student> list;
ArrayAdapter<Student> adapter;
Random rand = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_students);
//获取引用...
AddButton=(Button) findViewById(R.id.AddBtn);
NameEditText=(EditText) findViewById(R.id.StudentName);
CollegeEditText=(EditText) findViewById(R.id.College);
StudentListView=(ListView) findViewById(R.id.StudentListView);
//define the array list of students .
list=new ArrayList<Student>();
//set the communication between the ArrayList and the adapter.
adapter=new ArrayAdapter<Student>(this,android.R.layout.simple_list_item_1,list);
//set the communication between the Adapter and the ListView.
StudentListView.setAdapter(adapter);
OnClickListener listener=new OnClickListener() {
@Override
public void onClick(View v) {
int ID=rand.nextInt(50) + 1;
Student student=new Student();
student.setID(ID);
student.setName(NameEditText.getText().toString());
student.setCollege(CollegeEditText.getText().toString());
list.add(student);
NameEditText.setText("");
CollegeEditText.setText("");
adapter.notifyDataSetChanged();
}
};
AddButton.setOnClickListener(listener);
}}
如您所见,我创建了一个学生类和学生列表,并使用数组适配器将值添加到 ListView。
我真正想要的是自定义我的 ListView,以便列表视图的每一行看起来像这样
所以我将 Array Adapter 类自定义为 Student Array Adapter,如下代码:
class StudentAdapter extends ArrayAdapter <Student>{
public Context context;
public List<Student>students;
public StudentAdapter(@NonNull Context context, List<Student> list) {
super(context,R.layout.student_row, list);
this.context=context;
this.students=list;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.student_row, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.Name);
TextView college = (TextView) rowView.findViewById(R.id.College);
//下一步做什么???
}
}
我想设置学生行中每个文本视图的值 如何完成我的学生适配器?
【问题讨论】:
标签: android listview android-edittext android-arrayadapter textview