Expandable list style Change? - android

while i am searching for examples to make list of answers in expandable list i found code which use 4 java classes and one xml with expand list but not use xml for parent and child and i want to change text color and check box color
XML
<Spinner
android:id="#+id/coursescomplaint"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_gravity="center"
android:spinnerMode="dialog"
style="#style/spinner_style"/>
<ExpandableListView
android:id="#+id/expandcomplaintcourse"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/Button"
android:text="Submit"
android:layout_gravity="center"/>
JAVA
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Complaint extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static List<Answers> questions;
private ExpandableListView expandableListView;
private AnswersAdabter adapter;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint);
LoadQuestions();
expandableListView = (ExpandableListView)findViewById(R.id.expandcomplaintcourse);
adapter = new AnswersAdabter(this, questions);
expandableListView.setAdapter(adapter);
// The choice mode has been moved from list view to adapter in order
// to not extend the class ExpansibleListView
adapter.setChoiceMode(AnswersAdabter.CHOICE_MODE_SINGLE_PER_GROUP);
// Handle the click when the user clicks an any child
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
adapter.setClicked(groupPosition, childPosition);
return false;
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.coursescomplaint);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Course1");
categories.add("Course2");
categories.add("Course3");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private void LoadQuestions() {
questions = new ArrayList<Answers>();
ArrayList<String> citiesAustralia = new ArrayList<String>(
Arrays.asList("Brisbane", "Hobart", "Melbourne", "Sydney"));
questions.add(new Answers("Australia", citiesAustralia));
ArrayList<String> citiesChina = new ArrayList<String>(
Arrays.asList("Beijing", "Chuzhou", "Dongguan", "Shangzhou"));
questions.add(new Answers("China", citiesChina));
ArrayList<String> citiesIndia = new ArrayList<String>(
Arrays.asList("Bombay", "Calcutta", "Delhi", "Madras"));
questions.add(new Answers("India", citiesIndia));
ArrayList<String> citiesNewZealand = new ArrayList<String>(
Arrays.asList("Auckland", "Christchurch", "Wellington"));
questions.add(new Answers("New Zealand", citiesNewZealand));
ArrayList<String> citiesRussia = new ArrayList<String>(
Arrays.asList("Moscow", "Kursk", "Novosibirsk", "Saint Petersburg"));
questions.add(new Answers("Russia", citiesRussia));
}
}

Related

In android using OnClickListner for expandable listview

I am new to android please help me out for this problem.
In expandable list view clicking on each child list new activity should open.
here is my code
package com.example.index;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
public class IndexMainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index_main);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Part 1");
listDataHeader.add("Part 2");
listDataHeader.add("Part 3");
// Adding child data
List<String> parta = new ArrayList<String>();
parta.add("Sweet Hour Of Prayer");
parta.add("Prayer and Royal Family");
parta.add("The Holy Bible-King James Version");
parta.add("William shakespeare - Scriptres about prayer");
List<String> partb = new ArrayList<String>();
partb.add("Samuel Rutherford/scriptures-Thankfulness");
List<String> partc = new ArrayList<String>();
partc.add("Matthew Henry/Scriptures on - Faith");
partc.add("John Wesley/Scriptures on - Freedom");
partc.add("Charles Simeon/Scriptures on -Protection");
partc.add("Christmas Evans/Scriptures on - Guidance");
listDataChild.put(listDataHeader.get(0), parta); // Header, Child data
listDataChild.put(listDataHeader.get(1), partb);
listDataChild.put(listDataHeader.get(2), partc);
}
}
there are three list i.e part a , part b and part c now by clicking on part a i will get four child list by clicking on first child list i.e Sweet Hour of prayer new activity should open.
Try Below Code:
public class MyActivity extends Activity implements ExpandableListView.OnChildClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
Toast.makeText(getApplicationContext(), "Go to Activity :: "+childPosition, Toast.LENGTH_LONG).show();
return true;
}
}
There is a onChildClickListener for ExpandableListView. Check this code:
yourListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Open activity using intent...
return false;
}
});
Hope it helps!

Simple list item multiple choice not selecting items

I've created an array list and display it in a list view with simple list item multiple choice but i cannot check or tick the items on the list, when i click on the items nothing happens. Please check my code below and tell me what i am doing wrong.
package com.example.arrays;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
public class MainActivity extends Activity {
ListView showList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView show = (TextView)findViewById(R.id.txtShow);
final Random generate = new Random();
showList = (ListView)findViewById(R.id.listView1);
final String[] myAttraction = new String[4];
myAttraction[0]= "Walter Sisulu National Botanical Garden ";
myAttraction[1]= "Coca-Cola Dome";
myAttraction[2]= "Promusica Theatre";
myAttraction[3]= "Unisa Science Campus";
Button arrays = (Button)findViewById(R.id.button1);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
}
});
showList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add a OnItemClickListener like this to check/uncheck the CheckedTextView when user click on an item
showList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// change the checkbox state
CheckedTextView checkedTextView = ((CheckedTextView)view);
checkedTextView.setChecked(!checkedTextView.isChecked());
}
});
change your code as following....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
}
});
showList.setOnItemClickListener(new OnItemClickListener() {
public boolean onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
Set choiceMode property of your list to multipleChoice. I'm implementing multiple choice list in such a way in my applications, and it surely works.
Change this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
To this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
showList.setAdapter(adapter);
Just Add this line if you have a ListView and have selected simple_list_item_multiple_choice and you are unable to interact with the checkbox.
YourListViewName.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

AutoCompleteTextView OnItemClick position is always "0"

the adapter works fine, but i don't understand why the position in OnItemClick is always "0"
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int pos=position;
}
});
Don't ask me why, but the argument position in method OnItemClickListener.onItemClick holds the index relative to the AutoCompleteTextView's dropdown list, not the position in your adapter array (in your case regions)!
So, to find the item's real position you must get the string selected in the dropdown and find its index in the adapter array:
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getItemAtPosition(position);
int pos = Arrays.asList(regions).indexOf(selected);
}
});
I had the same issue: I couldn't manage to get the position, but I've figured out how to retrieve the whole object selected by the user (if any), having an ID field, which in my case is all I need.
The trick is not to use an ArrayAdapter<String> for the suggested items, but an ArrayAdapter<MyObject>, where MyObject overrides the toString() method.
For instance:
public class Country extends Object {
public int id;
public Country(int id) {
this.id = id;
}
#NonNull
#Override
public String toString() {
switch (id) {
case 0:
return "Albania";
case 1:
return "Romania";
case 2:
return "Ucraina";
case 3:
return "Russia";
default:
return "Unknwon";
}
}
}
...
private AutoCompleteTextView mNationAtv;
private Button mTestBtn;
private final Country[] COUNTRIES = {
new Country(0),
new Country(1),
new Country(2),
new Country(3)
};
...
// use object array for adapter
ArrayAdapter<Country> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
mNationAtv.setAdapter(adapter);
mTestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayAdapter<Country> ada = (ArrayAdapter<Country>) mNationAtv.getAdapter();
int nItems = ada.getCount();
// default Country unknown
Country selItem = new Country(5);
if (nItems > 0) {
selItem = (Country) ada.getItem(0);
}
Log.d(TAG,
"onClick(): nItems=" + nItems + ", selItem.name=" + selItem.toString()
+ ", selItem.id=" + selItem.id);
}
});
...
Logs:
when the AutocompleteTextView value matches an item in the dropdown:
onClick(): nItems=1, selItem.name=Ucraina, selItem.id=2
when the value is blank:
onClick(): nItems=4, selItem.name=Albania, selItem.id=0
when the value isn't blank but doesn't match any item in the dropdown:
onClick(): nItems=0, selItem.name=Unknown, selItem.id=5
You might want to fetch this value in the OnItemClickListener()::onItemClick() method, invoked avery time the user clicks an item in the dropdown, or outside of it, i.e. for validation.
I put this in a simple example and it works correctly for me. See below:
package com.example.autocompletetv;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
public class AutoCompleteActivity extends ListActivity {
public static final String TAG = AutoCompleteActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete);
String[] regions = {"One", "Two", "Three", "Four", "Five"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
this.setListAdapter(adapter);
this.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "postion was " + position);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_complete, menu);
return true;
}
}
When I click I get:
12-09 19:13:30.617: I/AutoCompleteActivity(1883): postion was 2
12-09 19:13:31.997: I/AutoCompleteActivity(1883): postion was 3
12-09 19:13:34.687: I/AutoCompleteActivity(1883): postion was 4
12-09 19:13:37.028: I/AutoCompleteActivity(1883): postion was 0

ActionBarActivity of "android-support-v7-appcompat" and ListActivity in Same activity

How to use ActionBarActivity of "android-support-v7-appcompat" in the activity which Extends the ListActivity.
For Example I have an Activity
public class xxxxxListActivity
extends ListActivity implements OnItemSelectedListener {
// ...................
}
In the above activity i want to use "ActionBarActivity" but as java dosent support multiple inheritance I am not able to get it working.
Here's an implementation of ActionBarListActivity:
public abstract class ActionBarListActivity extends ActionBarActivity {
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
Just like regular ListActivity, you'll need a layout that contains a ListView with the ID android.R.id.list ("#android:id/list" in XML).
The spiel in getListAdapter() is to handle cases where header views have been added to the ListView. Seems like ListView sets its own adapter to a HeaderViewListAdapter, so we have to try and get the wrapped adapter to prevent casting errors.
Edit: Try adding this function to satisfy the need for onListItemClick:
protected void onListItemClick(ListView lv, View v, int position, long id) {
getListView().getOnItemClickListener().onItemClick(lv, v, position, id);
}
Maybe you can try to extend ActionBarActivity and for default layout for that activity set some layout that has ListView.
Something like this:
public class AlarmListActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_with_list_view);
ListView lv = (ListView) findViewById(R.id.listView1);
// populate list view
}
}
and correcponding layout file:
<LinearLayout>
<ListView
android:id="#+id/listView1">
</ListView>
</LinearLayout>
Instead of creating the layout in XML, I decided to do it in code. The file a is a single drop in replacement in your code.
package com.stackoverflow.free.examples;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
/**
* based of https://raw.githubusercontent.com/android/platform_frameworks_base/d6c1919779acb042392615637b9007e0c4b89023/core/java/android/app/ListActivity.java
* Created by elcuco on 5/27/2014.
*/
#SuppressWarnings("UnusedDeclaration")
public class SupportListActivity extends ActionBarActivity {
protected ListAdapter mAdapter;
protected ListView mList;
protected TextView mEmptyMessage;
#Override
protected void onCreate(Bundle savedBundle)
{
super.onCreate(savedBundle);
mEmptyMessage = new TextView(this);
mEmptyMessage.setText("No results");
mList = new ListView(this);
mList.setEmptyView(mEmptyMessage);
LinearLayout ll = new LinearLayout(this);
ll.addView(mEmptyMessage, TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
ll.addView(mList, TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
setContentView(ll);
}
public void setListAdapter(ListAdapter adapter) {
synchronized (this) {
mAdapter = adapter;
mList.setAdapter(adapter);
}
}
/**
* Get the activity's list view widget.
*/
public ListView getListView() {
return mList;
}
/**
* Set the currently selected list item to the specified
* position with the adapter's data
*
* #param position the position on list to select
*/
public void setSelection(int position) {
mList.setSelection(position);
}
/**
* Get the position of the currently selected list item.
*/
public int getSelectedItemPosition() {
return mList.getSelectedItemPosition();
}
/**
* Get the cursor row ID of the currently selected list item.
*/
public long getSelectedItemId() {
return mList.getSelectedItemId();
}
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
onListItemClick((ListView)parent, v, position, id);
}
};
/**
* This method will be called when an item in the list is selected.
* Subclasses should override. Subclasses can call
* getListView().getItemAtPosition(position) if they need to access the
* data associated with the selected item.
*
* #param l The ListView where the click happened
* #param v The view that was clicked within the ListView
* #param position The position of the view in the list
* #param id The row id of the item that was clicked
*/
protected void onListItemClick(ListView l, View v, int position, long id) {
}
}
my answer based on accepted one, and also contains onListItemClick implementation. But it has a problem with empty view.
public abstract class ActionBarListActivity extends ActionBarActivity {
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
mListView.setOnItemClickListener(mOnClickListener);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
protected void onListItemClick(ListView l, View v, int position, long id) { }
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
onListItemClick((ListView) parent, v, position, id);
}
};
}
This solution is based on the accepted solution by #patrick. Here is the full code:
First the XML layout file activity_main.xml. Notice that I have an ListView with ID entryList
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.MainActivity" >
<ListView
android:id="#+id/entryList"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Next is my own ActionBarListActivity. You'd notice some changes. I wanted to make it generic and reusable as possible.
package com.example.api;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public abstract class ActionBarListActivity extends ActionBarActivity {
private final class ListOnItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> lv, View v, int position, long id) {
onListItemClick((ListView) lv, v, position, id);
// String str = ((TextView) arg1).getText().toString();
// Toast.makeText(getBaseContext(), str,
// Toast.LENGTH_LONG).show();
// Intent intent = new Intent(getBaseContext(),
// your_new_Intent.class);
// intent.putExtra("list_view_value", str);
// startActivity(intent);
}
}
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
initListView();
}
return mListView;
}
private void initListView() {
mListView = (ListView) findViewById(getListViewId());
if (mListView == null) {
throw new RuntimeException(
"ListView cannot be null. Please set a valid ListViewId");
}
mListView.setOnItemClickListener(new ListOnItemClickListener());
}
protected abstract int getListViewId();
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected void onListItemClick(ListView lv, View v, int position, long id) {
// No default functionality. To override
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
Next is my MainActivity extending the above class.
package com.example;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.api.ActionBarListActivity;
public class MainActivity extends ActionBarListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.d("click", "Position click " + position);
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
#Override
protected int getListViewId() {
return R.id.entryList;
}
}
Basically, by overriding onListItemClick() you can say what to do when user accepts something.
Let me know your thoughts/issues in the comments.
Cheers
Add following line of code to your class and make sure that the class implements AdapterView.OnItemClickListener:
getListView().setOnItemClickListener(this);

Android ListView pass data to another listview

How to write the code that can pass data from one lisview to another listview like if i select BMW from the car brand list i will be able to choose a particular car series that in a listview
main.XML
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
CarActivity.JAVA
package car.brand.test;
package car.brand.test;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class CarActivity extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "BMW", "Mercedes","Nissan"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
}
You don't need to pass data to another ListView, only one ListView is needed to achieve what you desire. You will have to do the mapping yourself, i.e. BMW maps to a list(java.util.ArrayList) that contains all BMW car series models, and Mercedes maps to a list that contains all Mercedes car series models, etc.
When you select a car brand, you swap the underlying dataset for the ListView and call notifyDataSetChanged().
snippet:
MyAdapter myAdapter = ...;
Map<String, List<String>> carSeriesMap = ...;
protected void onListItemClick(ListView l, View v, int position, long id) {
String brand = (String) getListAdapter().getItem(position);
List<String> carSeriesList = carSeriesMap.get(brand);
// set carSeriesList as the underlying dataset for the adapter
myAdapter.setDataset(carSeriesList);
}
class MyAdapter extends BaseAdapter {
List<String> dataset;
public void setDataset (List<String> newDataset) {
dataset = newDataset;
notifyDataSetChanged();
}
public View getView(int position, ......) {
// get data from dataset
String text = dataset.get(position);
// other code here...
}
}

Categories

Resources