2012-03-28 56 views
1

確定我已經搜索並發現了一些解決方案,似乎爲別人打工,雖然我無法弄清楚了我自己......列表視圖滾動到頂部上刪除

「的問題是,你正在創建一個新的適配器每次你重新加載數據,這不是你應該如何使用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> 

回答

0

你可以做的一件事是,在刷新ListView之前獲取ListView項目的可見位置,然後設置位置刷新ListView後。

我希望你延長你的ActivityListActivity

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

編輯

在你fillData()函數調用setListAdapter(notes);添加更多的線組的ListView顯示最後一行這樣後,

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

即時通訊仍然是新的和困惑。我需要更多細節。 mListView不能是resolvd。 – xaaam 2012-03-28 02:46:43

+0

mListView是ListView的實例。我在編輯我的答案。 – 2012-03-28 04:33:42

+0

確定可用於刪除的ty讓我試試看看我是否可以讓它工作,當我關閉/打開應用程序 – xaaam 2012-03-28 04:43:03