I am trying to create a listview that when you click on an entry you may modify it and after hitting confirm it will still show the entry you just modified instead of scrolling to the top.
made advised changes and after leaving the edit activity it still scrolls to the top and does not find the correct scroll position. am i missing something?
static int firstPosition = 0;
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
ListView mListView = getListView();
firstPosition = mListView.getFirstVisiblePosition();
c.moveToPosition(position);
Intent i = new Intent(this, QuoteEdit.class);
i.putExtra(QuotesDBAdapter.KEY_ROWID, id);
i.putExtra(QuotesDBAdapter.KEY_QUOTES, c.getString(
c.getColumnIndexOrThrow(QuotesDBAdapter.KEY_QUOTES)));
startActivityForResult(i, ACTIVITY_EDIT);
}
public void onResume(int requestCode, int resultCode, Intent intent) {
ListView mListView = getListView();
if (mListView != null && firstPosition >= 0){
mListView.scrollTo(0,firstPosition);
// mListView.setSelection(firstPosition);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
try {
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mDbHelper.createQuote(title);
break;
case ACTIVITY_EDIT:
ListView mListView = getListView();
Long rowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);
if (rowId != null) {
String editTitle = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mDbHelper.updateQuote(rowId, editTitle);
mListView.setSelection(firstPosition);
}
fillData();
break;
}
}
catch (Exception ex){
Context context = getApplicationContext();
CharSequence text = ex.toString();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
Your editor is another
Activity, which you are calling withstartActivityForResult(). This line doesn’t actually stop here – it will continue processing the rest of the method, including themListView.setSelection(firstPosition);statement. In other words,setSelection()is called before the user gets to edit the value.When the editor
Activityis closed, it will return the result toonActivityResult(). In this method, you will need to tell it to scroll theListViewto the correct position again. So maybe something like this…And change your
onListItemClick()method to use the global variable, like this…Now, the
setSelection()method doesn’t change the scroll position, but you could try this…In
onListItemClick(), change to the following…And in
onActivityResult(), change to the following…Possibly also add the following code to the end of your
onResume()method (in your mainActivity), so that it is run when you return back to the mainActivity…