此問題的標題可能很差,但難以確定標題。所以這是一個問題。Android從自定義ListView訪問元素
我有一個應用程序打開一個數據庫,並根據內容創建一個自定義的ListView。所以這個過程中涉及到幾個文件:
Main.java - opens the database and stores the List<MyClass> of contents
main.xml - main activity layout with the ListView
MyAdapter.java - extends BaseAdapter and calls MyAdapterView based on the context
MyAdapaterView.java - inflates the View from MyAdapater based on row.xml
row.xml - layout of each custom row of the ListView
這工作正常。我是Android新手,但在結構上,這似乎是每個人都建議構建自定義ListView的方式。
如何從ListView中檢索數據?例如,該行的一部分是複選框。如果用戶按下複選框來激活/停用特定行,那麼我如何通知主應用程序呢?
感謝,
編輯:
Main.java
public class MyApplication extends Activity
implements OnItemClickListener, OnItemLongClickListener
{
private List<MyClass> objects;
private ListView lvObjects;
private MyAdapter myAdapter;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
objects = new ArrayList<MyClass>(); // setup the list
lvObjects = (ListView)findViewById(R.id.lvObjectList);
lvObjects.setOnItemClickListener(this);
lvObjects.setOnItemLongClickListener(this);
loadDatabase(DATABASE);
myAdapter = new MyAdapter(this, objects);
lvObjects.setAdapter(myAdapter);
}
...
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
// This is executed when an item in the ListView is short pressed
}
public void onItemLongClick(AdapterView<?> parent, View v, int position, long id)
{
// This is executed when an item in the ListView is long pressed
registerForContextMenu(lvObjects);
v.showContextMenu();
}
MyAdapter.java
public class MyAdapter extends BaseAdapter
{
private Context context;
private List<MyClass> list;
public RuleAdapter(Context context, List<MyClass> list)
{
this.context = context;
this.list = list;
}
...
public View getView(int position, View view, ViewGroup viewGroup)
{
MyClass entry = list.get(position);
return new MyAdapterView(context,entry);
}
}
MyAdapterView.java
public class MyAdapterView extends LinearLayout
{
public MyAdapterView(Context context, MyClass entry)
{
super(context);
this.setOrientation(VERTICAL);
this.setTag(entry);
View v = inflate(context, R.layout.row, null);
// Set fields based on entry object
// When this box is checked or unchecked, a message needs to go
// back to Main.java so the database can be updated
CheckBox cbActive = (CheckBox)v.findViewById(R.id.cbActive);
addView(v);
}
}
對,CheckBox需要ListView行的焦點,所以在XML文件中,我將CheckBox設置爲'android:focusable =「false」'。這工作,並允許我聽ListViews短期和長期點擊。但是現在,我如何聽CheckBox和行?當按下該行時,會彈出一個適當運行的ContextMenu。但是,當CheckBox被選中或未選中時,我需要將消息發送迴應用程序以更新數據庫。沒有'onClickListener'被激活,我該怎麼做? – linsek 2010-12-10 19:37:41
我用我最近研究過的一個例子更新了答案。我不確定這正是你要求的,但它使用listview中的複選框,並應該讓你沿着正確的方向(也許)。 – 2010-12-10 19:51:26
@Charlie - 我用主應用程序更新了我的帖子。我仔細看了你引用的例子,但我並不完全確定這是我正在尋找的。問題是我需要三個不同的過程發生。 1-當ListView行被短按時,執行一些執行。 2-長按ListView行時,拉出一個上下文菜單。 3-當該行中的CheckBox被選中或未選中時,更新數據庫,該對象要麼處於活動狀態,要麼處於非活動狀態。我已經實現onItemClick和onItemLongClick來滿足前兩個。 – linsek 2010-12-10 20:18:55