我是android中的新手。我嘗試使用自定義列表視圖,並有一些問題。我有2個片段,片段A顯示列表視圖,片段B添加新項目。當我點擊片段B中的按鈕添加時,片段A將顯示,我希望新項目將添加在列表視圖中,然後排序列表視圖按照Alphabel。每件事情看起來都很棒,但是當ListView中添加項目時,它總是位於列表視圖的末尾,並且沒有用舊項目進行排序。我的ListView只是排序我剛添加到列表視圖中的項目。例如:我的listview顯示名稱:Ironman,Captain,Warmachine。我添加新的名字是:敢於魔鬼,阿里巴巴,Songoku。 listView將顯示爲:Captain,Ironman,Warmachine,阿里巴巴,Dare Devil,Songoku。我希望我的列表視圖必須如此:阿里巴巴,隊長,DareDevel,Ironman,Songoku和warachine。任何人都可以讓我知道我該怎麼做?如何在添加新項目後對listview項目進行排序
這裏是我的代碼:
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:感謝您閱讀我的問題。
是你的意思重寫arrayAdapter中的notifyDataSetChanged()? –
如果您的getPosition()覆蓋返回正確的項目位置,則notifyDataSetChanged將重新創建具有更新位置的所有列表項。您不需要重寫notifyDatasetChanged(),只需修復getPosition()以返回您的有序列表項位置。 – Luciano
它不完全在這種情況下兄弟。我只是更新我的問題回答。謝謝你回答:) –