2012-03-28 6 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를 새로 고친 후

나는 당신이 당신의 fillData() 기능에

이 같은 마지막 행을 보여주기 위해 한 번 더 라인 세트 목록보기를 추가 setListAdapter(notes); 호출 한 후,

당신의 Activity

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

ListActivity으로 편집 확장하는 희망

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

메신저 여전히 새롭고 혼란 스럽습니다. 좀 더 자세한 정보가 필요해. mListView는 분석 할 수 없습니다. – xaaam

+0

mListView는 ListView의 인스턴스입니다. 나는 내 대답을 편집 중입니다. –

+0

삭제를 위해 작동하는 ok ty 내가 시도해보고 내가 닫을 때 작동하도록 만들 수 있는지 확인/응용 프로그램을 엽니 다 – xaaam