此问题的标题可能很差,但难以确定标题。所以这是一个问题。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