i managed change listview
's item position after close app, position goes before made changes.
what , how save item's arranged position?
populating listview
string[] savedfiles; string datadr; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_address); datadr = getapplicationinfo().datadir; showdirfile(datadr); } void showdirfile(string dirpth) { string path = dirpth+"/files"; log.d("files", "path: " + path); file f = new file(path); file file[] = f.listfiles(); log.d("files", "size: "+ file.length); savedfiles = new string[file.length]; (int i=0; < file.length; i++) { log.d("files", "filename:" + file[i].getname()); savedfiles[i] = file[i].getname(); } arrayadapter<string> adapter = new arrayadapter<string>(this, android.r.layout.simple_list_item_1, savedfiles); listview.setadapter(adapter); }
to change item position , save them array
collections collections; void positionchange(){ //to store arrays arraylist list<string> newlist = new arraylist<string>(arrays.aslist(mydatafiles)); //to item's position @ first item in array if multiple arrays exist string currentpos = string.valueof(intarraylist.get(0)); int oldpos = integer.valueof(currentpos); int newpos = oldpos-1; //swap position @ move list collections.swap(newlist, oldpos, newpos); //store arraylist data arrays mydatafiles = newlist.toarray(mydatafiles); intarraylist.clear(); adapter.notifydatasetchanged(); }
edit
do note items in array
filled datadr = getapplicationinfo().datadir;
perhaps need find way save arrangement position in directory?
as mentioned in comments, sharedpreferences
trick. initialize in oncreate
method.
// use member variable (private sharedpreferences prefs) prefs = this.getsharedpreferences("com.example.app", context.mode_private);
since position of item may change, wise store file name instead of postion. place onitemselected
(therefor have add listener listview).
listview.setonitemselectedlistener(new adapterview.onitemselectedlistener() { @override public void onitemselected(adapterview<?> parent, view view, int position, long id) { prefs.edit().putstring("yourkey", listview.getitematposition(position)).apply(); } });
to set correct position after starting app have position of file in savedfile
object.
loading string sharedpreferences
:
string filename = prefs.getstring("yourkey", "");
after initialization of listview , adapter iterate through list , compare strings. if string matches, take position , set listview object.
for(int = 0; < savedfiles.length; i++){ if(filename.equals(savedfiles[i])){ listview.setselection(i); break; } }
Comments
Post a Comment