【发布时间】:2010-12-10 17:23:11
【问题描述】:
这个问题的标题可能很糟糕,但很难确定一个标题。那么问题来了。
我有一个应用程序,它打开一个数据库并根据内容创建一个自定义 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 新手,但从结构上看,这似乎是每个人都建议构建自定义 ListViews 的方式。
如何从 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);
}
}
【问题讨论】:
标签: android listview android-layout adapter