我是android的新手。我尝试使用自定义列表视图并遇到一些问题。我有2个片段,片段A显示列表视图,片段B添加新项目。当我单击按钮添加片段B时,片段A将显示,我希望新项目将添加到列表视图中,然后排序列表视图跟随Alphabel。每件事看起来都很棒,但是当在ListView中添加项目时,它总是位于列表视图的末尾,并且没有使用旧项目进行排序。我的ListView只是将我刚刚添加到listview中的项目排序。例如:我的列表视图显示名称:Ironman,Captain,Warmachine。我添加的新名称是:Dare Devil,Alibaba,Songoku。 listView将显示为:Captain,Ironman,Warmachine,Alibaba,Dare Devil,Songoku。我希望我的列表视图必须如此:阿里巴巴,船长,DareDevel,Ironman,Songoku和warachine。任何人都可以让我知道我该怎么做?。
这是我的代码:
MainActivity
public class MainActivity extends AppCompatActivity implements IMainClass, ICommunicator{
private ArrayList<StudentModel> arrayListStudent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
displayFragment();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void findViewByID() {
}
@Override
public void displayFragment() {
MainFragment mainFragment = new MainFragment();
FragmentManager fragmentManager = this.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body,mainFragment, "main");
fragmentTransaction.commit();
}
@Override
public void eventClickButton() {
}
@Override
public void add(StudentModel studentModel) {
MainFragment mainFragment = (MainFragment)getSupportFragmentManager().findFragmentByTag("main");
mainFragment.addStudentToList(studentModel);
}
自定义适配器
public class ArrayAdapterStudent extends ArrayAdapter<StudentModel> {
List<StudentModel> listStudent;
@Override
public int getPosition(StudentModel item) {
return super.getPosition(item);
}
public ArrayAdapterStudent(Context context, int resource, List<StudentModel> objects) {
super(context, resource, objects);
this.listStudent = objects;
}
@Override
public StudentModel getItem(int position) {
return super.getItem(position);
}
@Override
public int getCount() {
return super.getCount();
}
@Override
public Context getContext() {
return super.getContext();
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_row_listview,parent,false);
viewHolder = new ViewHolder();
viewHolder.tvName = (TextView)convertView.findViewById(R.id.tv_name);
viewHolder.tvAge = (TextView)convertView.findViewById(R.id.tv_age);
viewHolder.tvClass = (TextView)convertView.findViewById(R.id.tv_class);
viewHolder.tvSubject = (TextView)convertView.findViewById(R.id.tv_subjects);
viewHolder.chkStudent = (CheckBox)convertView.findViewById(R.id.chk_student);
viewHolder.chkStudent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer)buttonView.getTag();
listStudent.get(getPosition).set_isChecked(buttonView.isChecked());
}
});
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.tvName.setText("Name: "+listStudent.get(position).get_name());
viewHolder.tvAge.setText("Age: "+listStudent.get(position).get_age()+"");
viewHolder.tvClass.setText("Class: "+listStudent.get(position).get_class());
viewHolder.tvSubject.setText("Subject: "+listStudent.get(position).get_subject());
viewHolder.chkStudent.setTag(position);
viewHolder.chkStudent.setChecked(listStudent.get(position).is_Checked());
return convertView;
}
ViewHolder
public class ViewHolder {
TextView tvName, tvAge,tvClass,tvSubject;
CheckBox chkStudent;
}
ListFragment
public class MainFragment extends Fragment implements IMainClass {
private ListView lvStudent;
private Button btnAdd;
ArrayAdapterStudent arrayAdapterStudent;
private ArrayList<StudentModel> arrayListStudent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listStudent();
Log.d("Test"," OnCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container,false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
findViewByID();
loadStudentToListView();
choosingStudentInListView();
deleteStudent();
eventClickButton();
Log.d("Test", " OnActivityCreate");
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void loadStudentToListView(){
/*Collections.sort(arrayListStudent, new Comparator<StudentModel>() {
@Override
public int compare(StudentModel lhs, StudentModel rhs) {
return lhs.get_name().compareTo(rhs.get_name());
}
});
*/
arrayAdapterStudent = new ArrayAdapterStudent(getActivity(),R.layout.custom_row_listview,arrayListStudent);
arrayAdapterStudent.sort(new Comparator<StudentModel>() {
@Override
public int compare(StudentModel lhs, StudentModel rhs) {
return lhs.get_name().compareTo(rhs.get_name());
}
});
lvStudent.setAdapter(arrayAdapterStudent);
arrayAdapterStudent.notifyDataSetChanged();
}
@Override
public void findViewByID() {
lvStudent = (ListView) getActivity().findViewById(R.id.lv_student);
btnAdd = (Button)getActivity().findViewById(R.id.btn_add);
}
@Override
public void displayFragment() {
}
@Override
public void eventClickButton() {
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddNewStudentFragment addNewStudentFragment = new AddNewStudentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, addNewStudentFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
private void choosingStudentInListView(){
lvStudent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StudentModel studentModel = arrayListStudent.get(position);
studentBundel(studentModel);
Log.d("Test", "Student " + studentModel.is_Checked() + "is click");
}
});
}
private void deleteStudent(){
lvStudent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(getActivity()).setTitle("Notification").setMessage("Are your sure deleting this student ?")
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
arrayListStudent.remove(position);
arrayAdapterStudent.notifyDataSetChanged();
}
}).setPositiveButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
return true;
}
});
}
private void studentBundel(StudentModel studentModel){
DetailStudentFragment detailStudentFragment = new DetailStudentFragment();
Bundle inforStudentBundel = new Bundle();
inforStudentBundel.putSerializable("student",studentModel);
detailStudentFragment.setArguments(inforStudentBundel);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body,detailStudentFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public ArrayList<StudentModel> listStudent(){
String name = "";
int age = 18;
String Subject[] = {"Android","IOS","Java",".NET","C#"};
int subjectPosition = 0;
arrayListStudent = new ArrayList<StudentModel>();
for (int i = 0; i < 10; i++){
//Add student name Angela =>group name A
name = "Angela "+i;
StudentModel studentA = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentA);
//Add student name Beta =>Group name B
name = "BeTa"+i;
StudentModel studentB = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentB);
//Add student name Cadic =>Group name B
name = "Cadic"+i;
StudentModel studentC = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentC);
//Add Student name David
name = "David"+i;
StudentModel studentD = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentD);
//Add Student name Electro
name = "Electro"+i;
StudentModel studentE = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentE);
//Add Student name Kame
name = "Kame"+i;
StudentModel studentK = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentK);
//add Student name Songoku
name = "Songoku"+i;
StudentModel studentS = new StudentModel(name,age,"TVO",Subject[subjectPosition].toString());
subjectPosition = subjectPosition++;
arrayListStudent.add(studentS);
}
return arrayListStudent;
}
public void addStudentToList(StudentModel studentModel){
arrayListStudent.add(studentModel);
// arrayAdapterStudent.notifyDataSetChanged();
Log.d(" Test", arrayListStudent+"aaaaa");
//
// What is different when use arrListStudent.add an
//arrayAdapterStudent.insert(studentModel,0);
}
添加片段
public class AddNewStudentFragment extends Fragment implements IMainClass {
private EditText edtName, edtAge, edtClass, edtSubject;
private Button btnAddNewStudent;
ICommunicator iCommunicator;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.add_student_fragment,container,false);
return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
findViewByID();
iCommunicator = (ICommunicator)getActivity();
eventClickButton();
}
@Override
public void findViewByID() {
edtName = (EditText)getActivity().findViewById(R.id.edt_name);
edtAge = (EditText)getActivity().findViewById(R.id.edt_age);
edtClass = (EditText)getActivity().findViewById(R.id.edt_class);
edtSubject = (EditText)getActivity().findViewById(R.id.edt_subject);
btnAddNewStudent = (Button)getActivity().findViewById(R.id.btn_add_new_student);
}
@Override
public void displayFragment() {
}
@Override
public void eventClickButton() {
btnAddNewStudent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = edtName.getText().toString();
int age = Integer.parseInt(edtAge.getText().toString());
String classes = edtClass.getText().toString();
String subject = edtSubject.getText().toString();
StudentModel studentModel = new StudentModel(name, age, classes, subject);
iCommunicator.add(studentModel);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStack();
}
});
}
ICommunicator界面
public interface ICommunicator {
public void add(StudentModel studentModel);
}
IMain界面
public interface IMainClass {
public void findViewByID();
public void displayFragment();
public void eventClickButton();
}
StudentModel
public void set_name(String _name) {
this._name = _name;
}
public int get_age() {
return _age;
}
public void set_age(int _age) {
this._age = _age;
}
public String get_class() {
return _class;
}
public void set_class(String _class) {
this._class = _class;
}
public String get_subject() {
return _subject;
}
public void set_subject(String _subject) {
this._subject = _subject;
}
}
p / s:谢谢你阅读我的问题。
答案 0 :(得分:0)
您可以在ArrayAdapter上调用notifyDataSetChanged()来刷新listview项目。
答案 1 :(得分:0)
在添加新学生后调用loadStudentToListView()
以对视图进行排序和刷新:
public void addStudentToList(StudentModel studentModel){
arrayListStudent.add(studentModel);
loadStudentToListView();
}
答案 2 :(得分:0)
最后我知道我的问题是什么。我的问题来自排序功能。此函数遵循ASCII标准代码,因此它在upercase和小写之间有区别。所以,如果我想在插入新项目后对列表视图进行排序。我需要将所有这些转换为upercase或小写。就我而言,这段代码将完全排序。
Collections.sort(arrayListStudent, new Comparator<StudentModel>() {
@Override
public int compare(StudentModel lhs, StudentModel rhs) {
return lhs.get_name().toUpperCase().compareTo(rhs.get_name().toUpperCase());
}