I am looking to integrate MergeAdapter into my project and I am having an issue trying to retrieve which section the user has clicked. I want to set it up so when user clicks any item in any section, the section number is returned so I know which section the user is in. The app I am working on requires this.
Code below sets up 3 sections with some data in each section.
public class SectionTesting extends Activity
{
ListView listView;
private MergeAdapter mergeAdapter = null;
private static final String[] items =
{ "One", "Two", "Three" };
Context context;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mergelayout);
context = this;
listView = (ListView) findViewById(R.id.mergeListView);
mergeAdapter = new MergeAdapter();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, new ArrayList<String>(
Arrays.asList(items)));
TextView sectionHeader = new TextView(this);
sectionHeader.setText("Section One");
mergeAdapter.addView(sectionHeader);
mergeAdapter.addAdapter(adapter);
TextView sectionHeaderTwo = new TextView(this);
sectionHeaderTwo.setText("Section Two");
mergeAdapter.addView(sectionHeaderTwo);
mergeAdapter.addAdapter(adapter);
TextView sectionHeaderThree = new TextView(this);
sectionHeaderThree.setText("Section Three");
mergeAdapter.addView(sectionHeaderThree);
mergeAdapter.addAdapter(adapter);
listView.setAdapter(mergeAdapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3)
{
Toast.makeText(
context,
"You clicked Section "
+ mergeAdapter.getSectionForPosition(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
I was hoping getSectionForPosition method would return the value I require, but it just returns 0 everytime. I tried calling the method getSections().length as well to check it was returning the correct number of sections, but again it comes back as 0 everytime.
Any help would be much appreciated!!
Edit
I managed to come up with this messy solution. In the MergeAdapter class, under the addView method, I added this line of code
view.setId(1000);
Then I added this method here
public int getSectionNumber(int position)
{
int section = 0;
for (ListAdapter piece : getPieces())
{
int size = piece.getCount();
if (position < size)
{
return section-=1;
}
position -= size;
if(size == 1)
{
if(piece.getItem(0) instanceof TextView)
{
TextView tv = (TextView) piece.getItem(0);
if(tv.getId() == 1000)
{
section++;
}
}
}
}
return (-1);
}
The code seems to work fine, its just a bit sloppy I think. If anyone can come up with a cleaner solution that would be much appreciated, if not, then I will just add this as the answer when I can and accept it