listview在删除时滚动到顶部

时间:2012-03-28 01:38:50

标签: java android android-listview

好的,我已经搜索过并找到了一些似乎对其他人有用的解决方案,虽然我无法为自己找到它...

“问题是你每次重新加载数据时都在创建一个新的适配器。这不是你应该如何使用ListView及其适配器。而不是设置一个新的适配器(导致ListView重置其状态),只需更新已经在ListView上设置了适配器的内容。并且将为您保存选择/滚动位置。“

当我去修改一个条目或创建并回击而不是确认它保持我的位置时。

当我确认一个新条目时,它会转到顶部,我的新项目会转到底部......

如果我删除旧条目,它会转到顶部

当我关闭应用程序并重新打开它时,它会进入顶部。

主要是我希望它在删除项目时保持位置,当我关闭应用程序并重新打开它时。

当我创建一个新条目时,我希望它显示该条目

mDbHelper = new QuotesDBAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
addListenerOnButton();

} 
public void addListenerOnButton() {

    final Context context = this;

    button1 = (Button) findViewById(R.id.plus);

    button1.setOnClickListener(new OnClickListener() {

    //  @Override
        public void onClick(View arg0) {


            createNote();
        //    Intent intent = new Intent(context, QuoteEdit.class);
            //            startActivity(intent);   

        }

    });
}

private void fillData() {
        // Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllQuotes();
startManagingCursor(mNotesCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{QuotesDBAdapter.KEY_QUOTES};

        // and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};

// Now create a simple cursor adapter and set it to display

    SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.row, mNotesCursor, from, to);
setListAdapter(notes);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);


menu.add(0, DELETE_ID, 0, R.string.menu_delete);
menu.add(1, ACTIVITY_CREATE, 0, R.string.menu_insert);
}
public boolean onContextItemSelected;

public boolean onContextItemSelected(MenuItem item) {


AdapterView<ListAdapter> mList = null;

switch(item.getItemId()) {
case ACTIVITY_CREATE:
    try {
         Intent i = new Intent(this, QuoteEdit.class);
        startActivityForResult(i, ACTIVITY_CREATE);


    }
    catch (Exception ex)
    {
    Context context = getApplicationContext();
    CharSequence text = ex.toString();
    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, text, duration);
     toast.show(); 
    }
fillData();
return true;

case DELETE_ID:

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteQuote(info.id);
fillData();

return true;
}
return super.onContextItemSelected(item);
}


private void createNote() {
Intent i = new Intent(this, QuoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Cursor c = mNotesCursor;
    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);
}


@Override
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);
fillData();
break;
case ACTIVITY_EDIT:
Long rowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);
if (rowId != null) {
String editTitle = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mDbHelper.updateQuote(rowId, editTitle);
}
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(); <- something is wrong. fix later. ->
}
}
}

//适配器代码

private static class DatabaseHelper extends SQLiteOpenHelper {

DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS tblRandomQuotes");
onCreate(db);
}


}

    /**
         * Constructor - takes the context to allow the database to be
         * opened/created
         *
         * @param ctx the Context within which to work
     */
public QuotesDBAdapter(Context ctx) {
this.mCtx = ctx;
}

public QuotesDBAdapter open() throws SQLException {

mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close() {
mDbHelper.close();
}
public long createQuote(String quotes) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_QUOTES, quotes);

return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteQuote(long rowId) {

return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllQuotes() {

return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_QUOTES}, null, null, null, null, null);
}

public Cursor fetchQuote(long rowId) throws SQLException {

Cursor mCursor =

mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_QUOTES}, KEY_ROWID + "=" + rowId, null, null, null, null, null);

if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;

}

public boolean updateQuote(long rowId, String title) {
ContentValues args = new ContentValues();
args.put(KEY_QUOTES, title);

return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}

public int getAllEntries()
{
Cursor cursor = mDb.rawQuery("SELECT COUNT(quotes) FROM tblRandomQuotes", null);



if (cursor.moveToFirst()) {

    return cursor.getInt(0);

}

return cursor.getInt(0);

}
public String getRandomEntry()
{

Cursor cursor = mDb.rawQuery("SELECT quotes FROM tblRandomQuotes order by RANDOM() limit 1", null);

if(cursor.moveToFirst()) {

    return cursor.getString(0);

} else {

    return "No Quotes to display.";

}

}

/*

public String getRandomEntry()
{
int id = 1;
id = getAllEntries();

int rand = random.nextInt(id) + 1;
Cursor cursor = mDb.rawQuery("SELECT quotes FROM tblRandomQuotes WHERE _id = " + rand, null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);

}
*/

}

//并编辑活动代码

mQuoteText = (EditText) findViewById(R.id.title);

Button confirmButton = (Button) findViewById(R.id.confirm);


mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mRowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);

if (title != null) {
mQuoteText.setText(title);
                }
            }

confirmButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
Bundle bundle = new Bundle();


jokesToBeAdded = mQuoteText.getText().toString();

if(jokesToBeAdded.length() < 1) {
Toast.makeText(getApplicationContext(), "you forgot something.", Toast.LENGTH_LONG).show();

// createNote();
}

else{
Toast.makeText(getApplicationContext(), "done.", Toast.LENGTH_LONG).show();

bundle.putString(QuotesDBAdapter.KEY_QUOTES, jokesToBeAdded);

}


if (mRowId != null) {
bundle.putLong(QuotesDBAdapter.KEY_ROWID, mRowId);
}

Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}

});

}

protected EditText getString(String keyQuotes, String string) {
    // TODO Auto-generated method stub
    return null;
}
private void createNote() {
Intent i = new Intent(this, QuoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);

}
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:orientation="vertical">

<Button android:id="@+id/plus"
android:background="@drawable/selector"
android:layout_width="fill_parent"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
/>

<ListView 
    android:id="@android:id/list" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
      android:layout_above="@+id/plus"
>

</ListView>



<TextView android:id="@android:id/empty" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/noQ" 


 />


    </RelativeLayout>

1 个答案:

答案 0 :(得分:0)

你可以做的一件事是,在刷新ListView之前获取ListView项的可见位置,然后在刷新ListView之后设置位置。

我希望您将Activity扩展为ListActivity

ListView mListView = getListView();
int firstPosition = mListView.getFirstVisiblePosition();
setListAdapter(adapter);
mListView.setSelection(firstPosition);

修改

在致电fillData()后,在setListAdapter(notes);函数中再添加一行ListView以显示最后一行,

int firstPosition = mListView.getFirstVisiblePosition(); 
this.setSelection(firstposition)