When I had problems trying to fix the position of my listView items to the desired intent when filtered, and got info I could override the problem using a custom adapter, I have done that but I do not know how to assign the clicks to each items, please check below code:
public class IndexPageActivity extends Activity {
ListView listView;
EditText editTextB;
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener((OnItemClickListener) this);
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<SingleRow> pagelist;
Context context;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<SingleRow>();
Resources res = c.getResources();
String [] pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(new SingleRow(pagedatas[i]));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public Object getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return row;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
// TODO Auto-generated method stub
}
}
I will appreciate any help given. Thank Yhu!
EDIT
Will this work?
if (index == 0) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page1.html");
startActivity(i);
} else if (index == 1) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page2.html");
startActivity(i);
Edited ALL
I just got what you need, I added a filter to your baseAdapter and then on text change within the editText You filter the listView and then you go to the activity needed.
here is the full code but you need to bare in mind that I have changed the following:
I changed the pageList to ArrayList instead of
There is a bug in filtering that when I erase what I wrote in the EditText it doesnt update the ListView, you need to figure out why.
I changed the returned value of the function getItem(int i) from Object to String
Within the onItemClick you have to search for the name instead of the position.
here is the code:
public class IndexPageActivity extends Activity implements OnItemClickListener{
ListView listView;
EditText editTextB;
PagesAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
adapter1 = new PagesAdapter(this);
listView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listView.setOnItemClickListener(this);
editTextB.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
IndexPageActivity.this.adapter1.getFilter().filter(cs.toString());
adapter1.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Intent i;
String name = adapter1.getItem(position);
Log.d("id", name);
if (name.equals("Item1"))
{
i = new Intent(this, anActivity.class);
startActivity(i);
}
else if (name.equals("Item2"))
{
i = new Intent(this, anActivity2.class);
startActivity(i);
}
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements Filterable{
ArrayList<String> pagelist;
List<String> arrayList;
Context context;
String [] pagedatas;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<String>();
Resources res = c.getResources();
pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(pagedatas[i]);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public String getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
String temp=pagelist.get(i);
pagetitle.setText(temp);
return row;
}
public class filter_here extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ){
Result.values = pagelist;
Result.count = pagelist.size();
return Result;
}
ArrayList<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString;
for(int i = 0; i<pagelist.size(); i++){
filterableString = pagelist.get(i);
if(filterableString.toLowerCase().contains(filterString)){
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
pagelist = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new filter_here();
}
}
Two different ways for it:
1) If you want to use something like this at onCreate of your activity;
listView.setOnItemClickListener((OnItemClickListener) this);
You should implement OnItemClickListener to your activity:
IndexPageActivity extends Activity implements OnItemClickListener
and implement its onItemClick method at your activity. (also remove OnItemClickListener interface from your custom adapter)
2) You can simply use below without implementing OnItemClickListener to any class:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: handle row clicks here
}
I suggest 2nd option. That is easier.
Edit: This not relevant to your problem but you should reuse your views/rows at listView. Change your getView method to:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_row, parent, false);
} else {
view = convertView;
}
TextView pagetitle = (TextView) view.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return view;
}
Set your setOnItemClickListenerlike this:
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Your code here
//int position is the index of the list item you clicked
//use it to manipulate the item for each click
}
});
}
Related
I have an listview in my application and when I add search to my listview it dosen't work at all.
when I add those code to my project, getfilter doesn't resolve.
enter code here
public class MyActivity extends Activity {
InputStream in;
BufferedReader reader;
String line = "1";
public ListView listView;
VehicleAdapter adapter;
ArrayList<String> dataItems = new ArrayList<String>();
public int star = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
G.currentActivity = this;
setContentView(R.layout.main);
// Adad.setTestMode(true);
ReadText();
// String[] dataArray = dataItems.toArray(new String[0]);
//String[] dataArray = getResources().getStringArray(R.array.listdata);
//List<String> dataTemp = Arrays.asList(dataArray);
// dataItems.addAll(dataTemp);
listView = (ListView) findViewById(R.id.mainList);
EditText ed = (EditText) findViewById(R.id.editText1);
ArrayList<Bitmap> arr_bitmaps = new ArrayList<Bitmap>(4);
adapter = new VehicleAdapter(MyActivity.this, arr_bitmaps, dataItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// vaghti kar bar harfi vared kard josteju mikone :
MyActivity.this.adapter.getFilter().filter(arg0);
}
});
}
public class VehicleAdapter extends BaseAdapter {
ArrayList<String> arr_calllog_name = new ArrayList<String>();
public Activity context;
ArrayList<Bitmap> imageId;
public LayoutInflater inflater;
public VehicleAdapter(Activity context, ArrayList<Bitmap> arr_bitmaps, ArrayList<String> arr_calllog_name) {
super();
this.imageId = arr_bitmaps;
this.context = context;
this.arr_calllog_name = arr_calllog_name;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr_calllog_name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder {
TextView txtName;
ImageButton btn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.child_listview, null);
holder.txtName = (TextView) convertView.findViewById(R.id.childTextView);
holder.btn = (ImageButton) convertView.findViewById(R.id.childButton);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(PersianReshape.reshape(arr_calllog_name.get(position)));
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/B Morvarid_YasDL.com.ttf");
//holder.txtName.setTypeface(G.defaultFont);
holder.txtName.setTypeface(custom_font);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = arr_calllog_name.get(position);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.contact) {
Intent intent = new Intent(MyActivity.this, ContactUs.class);
startActivity(intent);
}
return super.onOptionsItemSelected(menuItem);
}
private void ReadText() {
try {
in = this.getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
dataItems.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my broblem is this code.
enter code here
MyActivity.this.adapter.getFilter().filter(arg0);
why getFilter() doesn't resolve?
Is it releted to my adaptor?
please help
why getFilter() doesn't resolve?
Because Filterable interface is not implemented in VehicleAdapter class.
To call adapter.getFilter().filter for Activity usng Adapter object need to implement Filterable interface in Adapter class and override getFilter.
See following example how to make Adapter Filterable:
Android Filter Custom ListView (BaseAdapter)
In custom adapter it would not work. this code for search will work in SimpleAdapter. For your adapter you have to write custom code for search.
Follow this link it would do as per your need (search filter in custom adapetr)
Custom Listview Adapter with filter Android
I would like to after clicking on the item child opened my new activity with the same name as the name of the item. That is item the "test" and if I click it open test.java class. I found a code that does this, but I do not know how to add it to my classes. Thank you for any help.
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<Alphabet> alphabetList;
private ArrayList<Alphabet> originalList;
public MyListAdapter(Context context, ArrayList<Alphabet> alphabetList){
this.context = context;
this.alphabetList = new ArrayList<Alphabet>();
this.alphabetList.addAll(alphabetList);
this.originalList = new ArrayList<Alphabet>();
this.originalList.addAll(alphabetList);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return alphabetList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<Waste> wasteList = alphabetList.get(groupPosition).getWasteList();
return wasteList.size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return alphabetList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<Waste> wasteList = alphabetList.get(groupPosition).getWasteList();
return wasteList.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Alphabet alphabet = (Alphabet) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
heading.setText(alphabet.getName().trim());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Waste waste = (Waste) getChild(groupPosition, childPosition);
if(convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(waste.getName().trim());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
public void filterData(String query)
{
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(alphabetList.size()));
alphabetList.clear();
if(query.isEmpty())
{
alphabetList.addAll(originalList);
} else {
for(Alphabet alphabet: originalList)
{
ArrayList<Waste> wasteList = alphabet.getWasteList();
ArrayList<Waste> newList = new ArrayList<Waste>();
for(Waste waste: wasteList)
{
if(waste.getName().toLowerCase().contains(query)){
newList.add(waste);
}
}
if(newList.size() > 0)
{
Alphabet nAlphabet = new Alphabet(alphabet.getName(), newList);
alphabetList.add(nAlphabet);
}
}
}
Log.v("MyListAdapter", String.valueOf(alphabetList.size()));
notifyDataSetChanged();
}
}
SegregateWasteActivity.java
public class SegregateWasteActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<Alphabet> alphabetList = new ArrayList<Alphabet>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.segregate_waste_activity);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
displayList();
expandAll();
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
listAdapter.filterData("");
expandAll();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
listAdapter.filterData(query);
expandAll();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
listAdapter.filterData(newText);
expandAll();
return false;
}
private void expandAll()
{
int count = listAdapter.getGroupCount();
for(int i = 0; i < count; i++)
{
myList.expandGroup(i);
}
}
private void displayList()
{
loadSomeData();
myList = (ExpandableListView) findViewById(R.id.expandableList);
listAdapter = new MyListAdapter(SegregateWasteActivity.this, alphabetList);
myList.setAdapter(listAdapter);
}
private void loadSomeData()
{
ArrayList<Waste> wasteList = new ArrayList<Waste>();
Waste waste = new Waste("Aerozol");
wasteList.add(waste);
waste = new Waste("Aaaa");
wasteList.add(waste);
Alphabet alphabet = new Alphabet("A", wasteList);
alphabetList.add(alphabet);
wasteList = new ArrayList<Waste>();
waste = new Waste("Butelka");
wasteList.add(waste);
alphabet = new Alphabet("B", wasteList);
alphabetList.add(alphabet);
}
}
and I want to this fragment throw:
#Override
protected void onListItemClick(ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = classNames[position];
try{
Class selected = Class.forName("com.odpad.odpadygdansk.waste." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
so I can click on an item from the list to go to the new activity with the same name as the class name.
I believe you want something like this:
expListView.setOnChildClickListener(new ExpandableListView
.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView elv, View view, int i,
int i2, long l) {
TextView tv = view.findViewById(R.id.name);
String name = (String) tv.getText();
try {
// Change package.name to your package
Class cls = Class.forName("package.name." + name);
Intent intent = new Intent(MainActivity.this, cls);
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
});
The code is pretty much self-explanatory.
You could use the position argument i received in the click callback, to fetch the specific name instead of findViewById(). That would be somewhat more efficient.
I have an ArrayList of Person class containing age and name of the person. In the adapter (extends BaseAdapter), I have two TextViews(for setting the values of age and name) and a checkbox. This is needed to be inflated into alert dialog.
How can I implement this using multichoice of the alert dialog.
Also I did look at some examples but did not understand about the boolean[] values attribute in the alert dialog, this is the code I have so far but it still needs to implement that multichoice mode..
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:choiceMode="multipleChoice">
</ListView>
My alertdialog..
AlertDialog.Builder ab=new AlertDialog.Builder(CustomListActivity.this);
LayoutInflater linf=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View v1=linf.inflate(R.layout.dialog_list, null);
ab.setView(v1);
//ab.setTitle("Select a group");
lv=(ListView) v1.findViewById(R.id.listView1);
ma=new MyAdapter(CustomListActivity.this, plist);
lv.setAdapter(ma);
And MYAdapter ..
public class MyAdapter extends BaseAdapter
{
Context ctx;
ArrayList<Person> plist;
LayoutInflater linf;
public PersonHolder ph=null;
public MyAdapter(Context ctx, ArrayList<Person> plist) {
super();
this.ctx = ctx;
this.plist = plist;
}
public class PersonHolder
{
public TextView age;
public TextView name;
public CheckBox check;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return plist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return plist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=linf.inflate(R.layout.row_item, null);
ph=new PersonHolder();
ph.age=(TextView) convertView.findViewById(R.id.text1);
ph.name=(TextView) convertView.findViewById(R.id.text2);
ph.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(ph);
}
else
{
ph=(PersonHolder) convertView.getTag();
}
Person p=(Person) getItem(position);
ph.age.setText(p.getAge());
ph.name.setText(p.getName());
ph.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// if(ph.check.isChecked())
// {
ph.check.setSelected(arg1);
// }
// else
// {
// ph.check.setSelected(false);
// }
}
});
return convertView;
}
}
Change your adapter to following and just call getSelected on adapter.
public class MyAdapter extends BaseAdapter
{
Context ctx;
ArrayList<Person> plist;
LayoutInflater linf;
public PersonHolder ph=null;
private ArrayList<Integer> selected=new ArrayList<Integer>();
public MyAdapter(Context ctx, ArrayList<Person> plist) {
super();
this.ctx = ctx;
this.plist = plist;
}
public class PersonHolder
{
public TextView age;
public TextView name;
public CheckBox check;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return plist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return plist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=linf.inflate(R.layout.row_item, null);
ph=new PersonHolder();
ph.age=(TextView) convertView.findViewById(R.id.text1);
ph.name=(TextView) convertView.findViewById(R.id.text2);
ph.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(ph);
}
else
{
ph=(PersonHolder) convertView.getTag();
}
Person p=(Person) getItem(position);
ph.age.setText(p.getAge());
ph.name.setText(p.getName());
ph.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// if(ph.check.isChecked())
// {
ph.check.setSelected(arg1);
if(arg1){
selected.add(position);
}else{
selected.remove(position);
}
// }
// else
// {
// ph.check.setSelected(false);
// }
}
});
return convertView;
}
public ArrayList<Integer> getSelected(){
return selected;
}
}
I have created a multichoice dialog myself, this is what i am doing, basically you need to catch each click to the listview and memorize whatever it is you selected/set there.
private void startDayPickerDialog() {
String[] days = getActivity().getResources().getStringArray(R.array.dayNames);
days = Arrays.copyOf(days, 7);
final Adapter a = new Adapter(getActivity());
AlertDialog d = new AlertDialog.Builder(getActivity())
.setTitle(R.string.repeat)
.setAdapter(a, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton(R.string.done, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
d.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> lv, View view, int position, long id) {
CheckBox cb = (CheckBox)view.findViewById(R.id.checkbox);
cb.setChecked(!cb.isChecked());
a.getItem(position).setChecked(!a.getItem(position).isChecked());
}
});
d.setCanceledOnTouchOutside(true);
d.show();
}
I want to create an ExpandableListView with custom adapter, however it only show my title group and when I click on the title (to view the children items) it doesnt do anything
(I want to have only one group item, therefore the item group count is 1).
Please help me to find where am I wrong, thanks alot.
This is my adapter:
class chatListAdapter extends BaseExpandableListAdapter {
private String objectsIdInsideAdapter;
private List<String> commentsInsideAdapter = new ArrayList<String>();
private List<String> FacebookIdInsideAdapter=new ArrayList<String>();
private List<String> NamesInsideAdapter =new ArrayList<String>();
private Context mContext;
chatListAdapter(String objectId,Context ctx,List<String> comments,List<String> face,List<String> names){
objectsIdInsideAdapter=objectId;
mContext=ctx;
commentsInsideAdapter=comments;
FacebookIdInsideAdapter=face;
NamesInsideAdapter=names;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return NamesInsideAdapter.get(arg1);
}
#Override
public long getChildId(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View v,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = getLayoutInflater();
if(v==null){
v = inflater.inflate(R.layout.chat_item, parent, false);
}
String comment =commentsInsideAdapter.get(position);
Button sendCommentBtn =(Button) v.findViewById(R.id.chatitemSendComment);
TextView commentView= (TextView) v.findViewById(R.id.chateitemViewComment);
commentView.setText(comment);
TextView commentName =(TextView) v.findViewById(R.id.chatitemfreindName);
commentName.setText(NamesInsideAdapter.get(position));
EditText commentText= (EditText) v.findViewById(R.id.chatitemEnterComment);
commentText.setVisibility(View.GONE);
sendCommentBtn.setVisibility(View.GONE);
return v;
}
#Override
public int getChildrenCount(int arg0) {
// TODO Auto-generated method stub
return NamesInsideAdapter.size();
}
#Override
public Object getGroup(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public long getGroupId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater inflater = getLayoutInflater();
v = inflater.inflate(R.layout.chat_item_group_layout,parent, false);
}
TextView groupName = (TextView) v.findViewById(R.id.groupName);
TextView groupDescr = (TextView) v.findViewById(R.id.groupDescr);
groupName.setText("view comments");
groupDescr.setText("groupDSCR");
return v;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
and this is the code in the main Activity:
ExpandableListView chat =(ExpandableListView) v.findViewById(R.id.ExpList);
String faceids =facebookIdChatInside.get(position);
String comments = commentInside.get(position);
String namesChat =nameChatInside.get(position);
List<String> chatItems = new ArrayList<String>(Arrays.asList(comments.split(",")));
List<String> facebookids = new ArrayList<String>(Arrays.asList(faceids.split(",")));
List<String> namesList = new ArrayList<String>(Arrays.asList(namesChat.split(",")));
chatItems.add(" ");
facebookids.add(id);
namesList.add(name);
chatListAdapter chatA =new chatListAdapter(objectsId.get(position),profileContext,chatItems,facebookids,namesList);
chat.setAdapter(chatA);
I checked it, and those 3 Lists are not empty.
Reading your code i found 3 points that aren't so clear to me:
getGroup you return null? Why don't u return the real Object
getChildId you should return an unique id identifying your child
hasStableIds. You return false. You dont need to override this method.
If you want to have more information on ExpandableListView give a look at my blog here
You are using the ExpandableListView like a simple ListView why dont u consider to you a ListView?
I have a listview which is working fine just using simple_list_view1. But now I need to add an icon to the left. So i've created a iconrow.xml in res/layout/. When I try and set that as the layout it errors and wont let me use android.R.layout.iconrow,. Clearly i'm doing something wrong here! It's an array being built up that will populate the data.
My xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_delete" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
My code is:
Cursor c = db.rawQuery(SQLStatement, null);
if(c.getCount() != 0) {
Log.e("LocationListView", "Found Items");
c.moveToFirst();
ArrayList mItemName = new ArrayList();
final ArrayList mItemID = new ArrayList();
c.moveToFirst();
while(!c.isAfterLast()) {
mItemName.add(c.getString(c.getColumnIndex("Name")));
mItemID.add(c.getString(c.getColumnIndex(ColType)));
c.moveToNext();
}
rowCount = mItemName.size();
listView = (ListView) findViewById(R.id.lvLocation);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.iconrow, android.R.id.text1, mItemName);
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(adapter);
listView.setClickable(true);
The error is on the android.R.layout.iconrow
Any help will be appreciated.
Tom
EDIT: Here is my code now - The errors on tv.setText(mItemName.get(arg0).toString());
c.moveToFirst();
final ArrayList<String> mItemID = new ArrayList<String>();
c.moveToFirst();
while(!c.isAfterLast()) {
mItemName.add(c.getString(c.getColumnIndex("Name")));
mItemID.add(c.getString(c.getColumnIndex(ColType)));
c.moveToNext();
}
rowCount = mItemName.size();
listView = (ListView) findViewById(R.id.lvLocation);
// final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// R.layout.iconrow, R.id.text, mItemName);
tv.setText(mItemName.get(arg0).toString());
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(new CustomAdapter());
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = listView.getItemAtPosition(position);
String StationObjectID = mItemID.get(position);
Intent SwapPage = new Intent(arg1.getContext(), LocationListView.class);
SwapPage.putExtra("ID", StationObjectID);
SwapPage.putExtra("Type", Type);
startActivityForResult(SwapPage, 0);
}
});
} else {
Log.e("LocationListView", "Not Found Items");
Context context = getApplicationContext();
CharSequence text = "No data returned";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
db.close();
}
public void goBack(View view) {
if(Global.returnPage.equals("MainPage")) {
Intent addItem = new Intent(view.getContext(), MainPage.class);
startActivityForResult(addItem, 0);
} else {
Intent addItem = new Intent(view.getContext(), LocationListView.class);
addItem.putExtra("Type", Global.stepListType);
Log.e("PushThrough", Global.stepListType);
addItem.putExtra("ID", Global.stepListID);
Log.e("PushThrough", Global.stepListID);
startActivityForResult(addItem, 0);
}
}
public void addItem(View view){
Intent addItem = new Intent(view.getContext(), AddItem.class);
addItem.putExtra("Count", rowCount);
if(Adding.equals("Building")){
addItem.putExtra("Type", "0");
} else if(Adding.equals("Room")){
addItem.putExtra("Type", "1001");
addItem.putExtra("PrevID", dataID);
} else if (Adding.equals("Area")){
addItem.putExtra("Type", "532");
addItem.putExtra("PrevID", dataID);
}
startActivityForResult(addItem, 0);
}
public void onResume()
{
super.onResume();
Log.e("Tom", "resumed");
}
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return mItemName.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.iconrow, arg2,true);
ImageView iv=(ImageView)v.findViewById(R.id.icon);
TextView tv=(TextView)v.findViewById(R.id.text);
return v;
}
}
}
Create custom Adapter as
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return mItemName.size;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.iconrow, arg2,true);
ImageView iv=(ImageView)v.findViewById(R.id.icon);
TextView tv=(TextView)v.findViewById(R.id.text);
return v;
}
}
and then set this to your list as
listview.setAdapter(new CustomAdapter());
Another implementation is as follows:
public class CustomArrayAdapter extends ArrayAdapter<Applications>{
private MainActivity context;
private int layoutResourceId;
private int textresourceId;
ArrayList<Applications> objects=null;
public CustomArrayAdapter(MainActivity context, int resource,ArrayList<Applications> objects) {
super(context, resource);
this.context = context;
this.layoutResourceId = resource;
this.objects = objects;
Log.d("CustomArrayAdapter","Was here!!");
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return objects.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inf=getLayoutInflater();
View convertView=inf.inflate(R.layout.iconrow, arg2,true);
ImageView iv=(ImageView)v.findViewById(R.id.icon);
TextView tv=(TextView)v.findViewById(R.id.text);
return convertView;
}
}