2011-09-16 101 views
0

我的活動代碼,以獲得ListActivity項目的位置更新狀態檢查數據庫如何獲取點擊ListView的項目的位置?

public class ViewList extends ListActivity { 
private ListViewAdapter lAdapter; 
DBAdapter db; 
@Override 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 

    db = new DBAdapter(this); 
    db.open();  
    Cursor cursor = db.fetchAllDeliveryItem(); 
    lAdapter = new ListViewAdapter(getApplicationContext(),cursor);  
    //Toast.makeText(getApplicationContext(), cursor.getString(1), Toast.LENGTH_SHORT).show(); 
    setListAdapter(lAdapter); 

} 
private class ListViewAdapter extends CursorAdapter{ 


@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // TODO Auto-generated method stub 

     return super.getView(position, convertView, parent); 
    } 

public ListViewAdapter(Context context, Cursor c) { 
    super(context, c); 
    // TODO Auto-generated constructor stub 
} 




@Override 
public void bindView(View view, Context context, Cursor cursor) { 
    TextView tvListText = (TextView)view.findViewById(R.id.label); 
    CheckBox cbListCheck = (CheckBox)view.findViewById(R.id.check); 

    tvListText.setText(cursor.getString(cursor.getColumnIndex("itemname"))); 
    **cbListCheck.setChecked((cursor.getInt(cursor.getColumnIndex("delivered"))==0? false:true)); 
    cbListCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      db.updateItem(position);** 


     } 
    }); 

} 

@Override 
public View newView(Context context, Cursor cursor, ViewGroup parent) { 
    LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    return li.inflate(R.layout.receiverow, parent, false); 
} 

回答

4

你需要調用setOnItemClickListener您的ListView。其回調函數包含作爲參數點擊的視圖的位置。這裏有一個例子:

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

    public void onItemClick(AdapterView parent, View v, int position, long id){ 

     // DO STUFF HERE 

    } 
}); 

編輯:對不起,我以爲你使用一個ListView不是ListActivity。它更容易爲一個ListActivity,因爲你只要實現以下方法在ListActivity:

onListItemClick (ListView l, View v, int position, long id) 
+0

但我的佈局不是列表視圖 –

+0

然後簡單地實現:onListI在ListActivity中的temClick(ListView l,View v,int position,long id)。它在文檔中非常清楚:http://developer.android.com/reference/android/app/ListActivity.html – slayton

+0

我創建了一個int位置;並指定在onListItemClick方法this.position =位置,但它返回0,每一個項目我點擊:( –

0

當你擴展ListActivity可以重寫onListItemClick方法是這樣的:

@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    super.onListItemClick(l, v, position, id); 
    // Do stuff 
} 
0

你應該實現

onListItemClick

和覆蓋的方法:

@Override 
    protected void onListItemClick(ListView l, View v, final int position, long id) { 
     super.onListItemClick(l, v, position, id); 

Log.i("the Item clicked is at position : ", position); 

    } 
相關問題