The title for this question might be poor, but but it was hard to nail down a title. So here is the question.
I have an application that opens a database and creates a custom ListView based on the contents. So there are a few files involved in this process:
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
This works fine. I am new to Android, but structurally this seems to be how everyone recommends building custom ListViews.
How do I retrieve data from the ListView? For instance, part of the row is a checkbox. If the user presses the checkbox to activate/deactivate the particular row, how do I notify the main application about that?
Thanks,
EDIT:
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);
}
}