Get child view from ExpandableListView in FragmentActivity without childClick Event - android

I have several classes. First class extends from FragmentActivity, second class is adapter extends from BaseExpandableListAdapter. And Model Class.
First class:
public class CloseInformationTaskActivityList extends FragmentActivity implements ExpandableListView.OnChildClickListener {
private DAOFactory dao;
private ExpandListAdapter expAdapter;
private ExpandableListView expandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
//task with all information passed in intent by reference
PRTarea task = (PRTarea) b.getSerializable("Task");
dao = new DAOFactory(this.getApplicationContext());
List<PRParametros> parametrosList = dao.getParametrosDAO().getParamsByTaskId(task.getId());
if (parametrosList.size() > 0) {
setContentView(R.layout.activity_task_parameters_list);
expandList = (ExpandableListView) findViewById(R.id.paramsExpandableListView);
ArrayList<Group> expListItems = setParamsGroups(parametrosList);
expAdapter = new ExpandListAdapter(CloseInformationTaskActivityList.this, expListItems, this);
expandList.setOnChildClickListener(this);
expandList.setAdapter(expAdapter);
} else {
setContentView(R.layout.activity_no_param_error);
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
assert actionBar != null;
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setTitle(R.string.task_information_title);
actionBar.setIcon(R.drawable.ic_arrow_back_white_24dp);
}
private ArrayList<Group> setParamsGroups(List<PRParametros> parametrosList) {
ArrayList<Group> paramGroupList = new ArrayList<>();
ArrayList<Child> ch_list = null;
Group grupo;
String holdIdGroup = "0";
//secure check
if (parametrosList != null && parametrosList.size() > 0) {
for (int i = 0; i < parametrosList.size(); i++) {
PRParametros parametro = parametrosList.get(i);
String idGrupo = parametro.getIdGrupo();
if (!idGrupo.equals(holdIdGroup)) {
holdIdGroup = idGrupo;
grupo = new Group();
ch_list = new ArrayList<>();
grupo.setName(dao.getGruposParametrosDAO().getGrupoById(idGrupo).getDescripcion());
grupo.setItems(ch_list);
paramGroupList.add(grupo);
}
Child child = new Child();
child.setName(parametro.getNombre());
if(parametro.getIdTipo().equals("12")){
if(parametro.getValor() != null){
paramValue = dao.getListaParametrosDAO().getValueParamById(Integer.valueOf(parametro.getValor()));
}
}
child.setValue(paramValue);
child.setType(Integer.valueOf(parametro.getIdTipo()));
child.setParamId(Integer.valueOf(parametro.getId()));
if (ch_list != null) {
ch_list.add(child);
}
}
}
return paramGroupList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.btn_save_param:
saveParameters();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveParameters() {
Toast.makeText(getApplicationContext(),"Save parameters click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.save_parameters, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Child child = (Child) parent.getExpandableListAdapter().getChild(groupPosition,childPosition);
int itemType = child.getType();
switch (itemType){
case 12:
onCreateDialogSingleChoice(child, v);
break;
case 9:
openDateDialog(child, v);
break;
}
return false;
}
/**
* Open popup with single choice, refresh model data of child
* and assign selected value to textView
*
* #param child model with data
* #param view to asign selected value
*/
public void onCreateDialogSingleChoice(final Child child, final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
List<PRListaParametros> listaParametros = dao.getListaParametrosDAO().getListParamsById(child.getParamId());
List<String> values = new ArrayList<>();
for(int i = 0; i < listaParametros.size(); i++){
values.add(listaParametros.get(i).getDescripcion());
}
final String[] items = values.toArray(new String[listaParametros.size()]);
final TextView label = (TextView) ((RelativeLayout) view).getChildAt(1);
builder.setTitle(R.string.task_information_param_popup_title);
builder.setSingleChoiceItems(items, 75, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
label.setText(items[which]);
child.setValue(items[which]);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.task_information_param_popup_negative_button,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
label.setText("");
}
});
builder.show();
}
}
Second class:
/**
* Adapter for expandable list with parameters
*/
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private ArrayList<Group> groups;
private LayoutInflater mInflater;
public ExpandListAdapter(Context mContext, ArrayList<Group> groups) {
this.mContext = mContext;
this.groups = groups;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}
#Override
public boolean areAllItemsEnabled() {
return super.areAllItemsEnabled();
}
#Override
public View getChildView(int groupPosition, final int childPosition,
final boolean isLastChild, View convertView, ViewGroup parent) {
final Child child = (Child) getChild(groupPosition, childPosition);
final ViewHolder holder;
int itemType = child.getType();
holder = new ViewHolder();
if (itemType >= 1 && itemType <= 7) {
convertView = mInflater.inflate(R.layout.layout_edit_text_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param);
holder.editText = (EditText) convertView.findViewById(R.id.txt_task_detail_info_param_input);
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//refresh data in model
child.setValue(holder.editText.getText().toString());
}
});
}else if(itemType == 8){
convertView = mInflater.inflate(R.layout.layout_boolean_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_boolean_title);
holder.booleanSwitch = (Switch) convertView.findViewById(R.id.param_boolean_switch);
holder.booleanSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String switchValue = "false";
if(holder.booleanSwitch.isChecked()){
switchValue = "true";
}
child.setValue(switchValue);
//mParamListener.onParameterViewClick(v, child);
}
});
}else {
convertView = mInflater.inflate(R.layout.layout_text_view_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_text_view);
holder.txtClickWithValue = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_click_text_view);
}
convertView.setTag(holder);
if (itemType >= 1 && itemType <= 7) {
holder.txtLabel.setText(child.getName());
holder.editText.setText(child.getValue());
switch (itemType){
case 1:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
break;
case 2:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
break;
case 6:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
if(!holder.editText.getText().toString().isEmpty()){
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 4 no valido");
}
}
break;
case 7:
holder.editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
if(!holder.editText.getText().toString().equals("")){
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 6 no valido");
}
}
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 6 no valido");
}
}
});
break;
}
}else if(itemType == 8) {
boolean value = Boolean.valueOf(child.getValue());
holder.txtLabel.setText(child.getName());
if(value){
holder.booleanSwitch.setTextOn(mContext.getResources().getString(R.string.task_information_param_boolean_switch_on));
holder.booleanSwitch.setChecked(true);
}else{
holder.booleanSwitch.setTextOff(mContext.getResources().getString(R.string.task_information_param_boolean_switch_off));
holder.booleanSwitch.setChecked(false);
}
}else {
holder.txtLabel.setText(child.getName());
holder.txtClickWithValue.setText(child.getValue());
}
return convertView;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
//call notifyDataSetChanged() for refresh data model in view
}
public static class ViewHolder {
public TextView txtLabel;
public EditText editText;
public TextView txtClickWithValue;
public Switch booleanSwitch;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Group group = (Group) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.activity_task_parameters_group, null);
}
TextView groupTitle = (TextView) convertView.findViewById(R.id.param_group_name);
groupTitle.setText(group.getName());
TextView groupCount = (TextView) convertView.findViewById(R.id.param_group_count);
int countParam = getChildrenCount(groupPosition);
if(countParam > 1){
groupCount.setText(getChildrenCount(groupPosition) + " " +
mContext.getResources().getString(R.string.task_information_param_group_count_title));
}else{
groupCount.setText(getChildrenCount(groupPosition) + " " +
mContext.getResources().getString(R.string.task_information_param_group_count_title_single));
}
if (isExpanded) {
convertView.setBackgroundResource(R.color.group_param_expanded);
} else {
convertView.setBackgroundResource(0);
}
return convertView;
}
#Override
public int getChildType(int groupPosition, int childPosition) {
return super.getChildType(groupPosition, childPosition);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
/**
* #param ip the ip
* #return check if the ip is valid ipv4 or ipv6
*/
private static boolean isValidIp(final String ip) {
return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip);
}
}
Model Class
/**
* Model of each parameters
*/
public class Child {
private String name;
private String value;
private int type;
private int paramId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getParamId() {
return paramId;
}
public void setParamId(int paramId) {
this.paramId = paramId;
}
}
XML View of each child by type, possible type is EditText, TextView, Switch, popup list with single choice.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:id="#+id/txt_task_detail_info_param"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:minWidth="150dp"
android:focusable="false"
android:clickable="false"
android:padding="20dp"
android:textSize="14sp"
android:layout_toLeftOf="#+id/txt_task_detail_info_param_input"
android:layout_alignParentLeft="true" />
<EditText
android:id="#+id/txt_task_detail_info_param_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="150dp"
android:maxWidth="200dp"
android:ellipsize="end"
android:maxLines="1"
android:textSize="14sp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Layout have action bar with save button:
|------------------Save button--|
| <ExpandableList> | |
| group1 | |
| child1: textView EditText | |
| child2: textView Switch | |
| group2 | |
| child1: textView TextView | |
|-------------------------------|
I am trying to get values of child view for save it in database, before i need check each field by type for valid data.
Currently i am checking the values in adapter and works well. Possibly not the right way...
But how to get value of each view by type only clicking save button in FragmentActivity in action bar??
I am trying onChildClick but click event by editText not working. Thanks!
SOLVED
Now I have resolved, but I think is not the right way for do it.
In model class Child i created new field with View.
private View view;
and assigned complete View by type (editText,TextView, etc) in adapter getChildView for example:
child.setView(holder.editText);
and finally use in FragmentActivity
private void checkParameters() {
boolean validated = true;
int groupCount = expandList.getExpandableListAdapter().getGroupCount();
for (int i = 0; i < groupCount; i++) {
int childCount = expandList.getExpandableListAdapter().getChildrenCount(i);
for (int j = 0; j < childCount; j++) {
Child child = (Child) expandList.getExpandableListAdapter().getChild(i, j);
//secure check
if (child.getView() != null) {
int itemType = child.getType();
//only editText
if (itemType >= 1 && itemType <= 7) {
EditText ed = (EditText) child.getView();
//do something
}
}
}
}
}
Anyone know how to do this more efficiently???

Related

Highlight Header View of expandable list view if Its at least one Child View is highlighted on Android Studio

I want Header View on expandable List View is automatically changed background color right after initial program if there is at least one of Child View be highlighted
I get this program from http://tutorialscache.com/expandable-listview-android-tutorials/ as an example
Here is the ExpandableCustomAdapter Class
public class ExpandableCustomAdapter extends BaseExpandableListAdapter{
//Initializing variables
private List<String> headerData;
private HashMap<String, ArrayList<ChildDataModel>> childData;
private Context mContext;
private LayoutInflater layoutInflater;
// constructor
public ExpandableCustomAdapter(Context mContext, List<String> headerData,
HashMap<String, ArrayList<ChildDataModel>> childData) {
this.mContext = mContext;
this.headerData = headerData;
this.childData = childData;
this.layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getGroupCount() {
return this.headerData.size();
}
#Override
public int getChildrenCount(int headPosition) {
return this.childData.get(this.headerData.get(headPosition)).size();
}
#Override
public Object getGroup(int headPosition) {
return this.headerData.get(headPosition);
}
#Override
public Object getChild(int headPosition, int childPosition) {
return this.childData.get(this.headerData.get(headPosition))
.get(childPosition);
}
#Override
public long getGroupId(int headPosition) {
return headPosition;
}
#Override
public long getChildId(int headPosition, int childPosition) {
return this.childData.get(this.headerData.get(headPosition))
.get(childPosition).getId();
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
headerTv.setBackgroundColor( Color.BLUE );
return view;
}
#Override
public View getChildView(int headPosition, int childPosition, boolean islastChild, View view, ViewGroup viewGroup) {
ChildDataModel child = (ChildDataModel) getChild(headPosition, childPosition);
if (view == null) {
view = layoutInflater.inflate(R.layout.child_item, null);
}
TextView childTv = (TextView) view.findViewById(R.id.childTv);
ImageView childImg = (ImageView) view.findViewById(R.id.childImg);
childTv.setText(child.getTitle());
if(child.getTitle().equalsIgnoreCase( "China" ))
{
childTv.setBackgroundColor( Color.RED );
}
childImg.setImageResource(child.getImage());
return view;
}
#Override
public boolean isChildSelectable(int headPosition, int childPosition) {
return true;
}
}
Here is ChildDataModel Class
public class ChildDataModel {
long id;
int image;
String title;
public ChildDataModel(int id, String country, int image) {
this.setId(id);
this.setTitle(country);
this.setImage(image);
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
Log.d("response ","ID: "+getId()+" Title: "+getTitle());
return super.toString();
}
}
Here is MainActivity Class
public class MainActivity extends AppCompatActivity {
ExpandableCustomAdapter expandableCustomAdapter;
ExpandableListView expandableListView;
List<String> headerData;
HashMap<String,ArrayList<ChildDataModel>> childData;
ChildDataModel childDataModel;
Context mContext;
ArrayList<ChildDataModel> asianCountries,africanCountries,nAmericanCountries,sAmericanCountries;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
//initializing arraylists
headerData = new ArrayList<>();
childData = new HashMap<String,ArrayList<ChildDataModel>>();
asianCountries = new ArrayList<>();
africanCountries = new ArrayList<>();
nAmericanCountries = new ArrayList<>();
sAmericanCountries = new ArrayList<>();
// link listview from activity_main.xml
expandableListView = findViewById(R.id.expandAbleListView);
//populating data of world continents and their countries.
headerData.add("ASIA");
//adding countries to Asian continent
childDataModel = new ChildDataModel(1,"Afghanistan",R.drawable.afghanistan);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(2,"China",R.drawable.china);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(3,"India",R.drawable.india);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(4,"Pakistan",R.drawable.pakistan);
asianCountries.add(childDataModel);
childData.put(headerData.get(0),asianCountries);
headerData.add("AFRICA");
//adding countries to African continent
childDataModel = new ChildDataModel(1,"South Africa",R.drawable.southafrica);
africanCountries.add(childDataModel);
childDataModel = new ChildDataModel(2,"Zimbabwe",R.drawable.zimbabwe);
childData.put(headerData.get(1),africanCountries);
headerData.add("NORTH AMERICA");
//adding countries to NORTH AMERICA continent
childDataModel = new ChildDataModel(1,"Canada",R.drawable.canada);
nAmericanCountries.add(childDataModel);
childData.put(headerData.get(2),nAmericanCountries);
headerData.add("SOUTH AMERICA");
//adding countries to SOUTH AMERICA continent
childDataModel = new ChildDataModel(1,"Argentina",R.drawable.argentena);
sAmericanCountries.add(childDataModel);
childData.put(headerData.get(3),sAmericanCountries);
//set adapter to list view
expandableCustomAdapter = new ExpandableCustomAdapter(mContext,headerData,childData);
expandableListView.setAdapter(expandableCustomAdapter);
//child click listener
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int headPosition, int childPosition, long id) {
Toast.makeText(mContext,
headerData.get(headPosition)
+ " has country "
+ childData.get(
headerData.get(headPosition)).get(
childPosition).getTitle(), Toast.LENGTH_SHORT)
.show();
return false;
}
});
//group expanded
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int headPosition) {
if (lastExpandedPosition != -1
&& headPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = headPosition;
Toast.makeText(mContext,
headerData.get(headPosition) + " continent expanded",
Toast.LENGTH_SHORT).show();
}
});
//group collapsed
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int headPosition) {
Toast.makeText(mContext,
headerData.get(headPosition) + " continent collapsed",
Toast.LENGTH_SHORT).show();
}
});
//Group Indicator
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
parent.smoothScrollToPosition(groupPosition);
if (parent.isGroupExpanded(groupPosition)) {
ImageView imageView = v.findViewById(R.id.expandable_icon);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right));
} else {
ImageView imageView = v.findViewById(R.id.expandable_icon);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
}
return false ;
}
});
}
}
I expect to handle it without event like setOnChildClickListener, setOnGroupExpandListener,setOnGroupCollapseListener, etc. Thanks for help
change getGroupView to:
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
boolean hasSelected = false;
ArrayList<ChildDataModel> childs =
childData.get(headerData.getItemAtIndex(headPosition));
for(int i=0;i<childs.size();i++){
if(childs.get(i).isSelected){
hasSelected = true;
}}
if(hasSelected)
headerTv.setBackgroundColor( Color.BLUE );
else
headerTv.setBackgroundColor( Color.RED);
return view;
}
you most highlight the header view when getGroupView executed if childs highl sign selected chileds and if selected eny then highlight header
Thank you #hunixa siuri It does work well. However Code must be edited a little as below
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
boolean hasSelected = false;
ArrayList<ChildDataModel> childs = childData.get(headerData.get(headPosition));
for(int i=0;i<childs.size();i++){
if(childs.get(i).getTitle().equalsIgnoreCase( "China" )){
hasSelected = true;
}}
if(hasSelected)
view.setBackgroundColor( Color.BLUE );
else
view.setBackgroundColor( Color.RED);
return view;
}

ExpandableListView with ViewPager combination as its child

UPDATE - Added experimentation result
Is it possible to implement an ExpandableListView to have a viewpager child?
I tried to put viewpager as a child in ExpandableListView but it is not showing :( I also tried to add it under ScrollView but same result so I think it is a problem being under a scrollable view? But when I removed ScrollView it showed up. What can I do so they can go together?
This is what I am aiming for to do
And this is what happen when I tried to implement on my own code.
P.S. This is just a sampler and not yet finished. I have 3 children and my layout displayed thrice also with each item inside
can you check this API
https://developer.android.com/reference/android/widget/ExpandableListView
A view that shows items in a vertically scrolling two-level list
I made a sample in Java. Hope that helps!
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnClearChecks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear Checks" />
<Button
android:id="#+id/btnPutOrder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Put Order" />
</LinearLayout>
<ExpandableListView
android:id="#+id/expandedListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ExpandableListView>
</LinearLayout>
expanded_list_group.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="#+id/cb_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/tv_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textSize="30sp" />
</LinearLayout>
list_child_pager.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingStart="60dp">
<android.support.v4.view.ViewPager
android:id="#+id/layout_child"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
list_pager_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="#integer/pager_col_count"
android:rowCount="#integer/pager_row_count">
</GridLayout>
integers.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="pager_col_count">3</integer>
<integer name="pager_row_count">3</integer>
</resources>
ChildItemSample.java
public class ChildItemSample {
private boolean checked = false;
private String name;
private int qty;
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getName() {
return name;
}
public ChildItemSample(String name, int qty){
this.name = name;
this.qty = qty;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button clearChecks, putOrder;
ExpandableListView expandableListView;
ExpandableListPagerAdapter expandableListAdapter;
int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandedListView);
clearChecks = findViewById(R.id.btnClearChecks);
putOrder = findViewById(R.id.btnPutOrder);
List<String> listTitle = genGroupList();
expandableListAdapter = new ExpandableListPagerAdapter(this, getSupportFragmentManager(), listTitle, genChildList(listTitle));
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(lastExpandedPosition != -1 && (lastExpandedPosition != groupPosition)){
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
clearChecks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapter.clearChecks();
}
});
putOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<String> putOrder = expandableListAdapter.getOrderList();
StringBuilder msg = new StringBuilder();
for(int i=0; i<putOrder.size(); i++){
msg.append(putOrder.get(i));
msg.append("\n");
}
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<String> genGroupList(){
ArrayList<String> listGroup = new ArrayList<>();
for(int i=1; i<10; i++){
listGroup.add("Group: " + i);
}
return listGroup;
}
private Map<String, List<ChildItemSample>> genChildList(List<String> header){
Map<String, List<ChildItemSample>> listChild = new HashMap<>();
for(int i=0; i<header.size(); i++){
List<ChildItemSample> testDataList = new ArrayList<>();
int a = (int)(Math.random()*28);
for(int j=0; j<a; j++){
ChildItemSample testItem = new ChildItemSample("Child " + (j + 1), 0);
testDataList.add(testItem);
}
listChild.put(header.get(i), testDataList);
}
return listChild;
}
}
ExpandableListPagerAdapter.java:
public class ExpandableListPagerAdapter extends BaseExpandableListAdapter {
private int child_items_per_page;
private Context context;
private FragmentManager fm;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private static int checkedBoxesCount;
private boolean[] checkedGroup;
ExpandableListPagerAdapter(Context context, FragmentManager manager, List<String> listGroup, Map<String,
List<ChildItemSample>> listChild) {
this.context = context;
fm = manager;
this.listGroup = listGroup;
this.listChild = listChild;
checkedBoxesCount = 0;
checkedGroup = new boolean[listGroup.size()];
child_items_per_page = context.getResources().getInteger(R.integer.pager_col_count) *
context.getResources().getInteger(R.integer.pager_row_count);
}
#Override
public int getGroupCount() {
return listGroup.size();
}
#Override
//******* Special *******
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public String getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public ChildItemSample getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {
String itemGroup = getGroup(groupPosition);
GroupViewHolder groupViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_group, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);
groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);
groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
checkedGroup[pos] = !checkedGroup[pos];
for(ChildItemSample item : listChild.get(listGroup.get(pos))){
item.setChecked(checkedGroup[pos]);
}
notifyDataSetChanged();
}
});
view.setTag(groupViewHolder);
}else {
groupViewHolder = (GroupViewHolder)view.getTag();
}
groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, listChild.get(listGroup.get(groupPosition)).size()));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_child_pager, null);
ViewPager childLayout = rowView.findViewById(R.id.layout_child);
List<ChildItemSample> childItemSampleList = listChild.get(listGroup.get(groupPosition));
ChildPagerAdapter adapter = new ChildPagerAdapter(fm, childItemSampleList, child_items_per_page);
childLayout.setAdapter(adapter);
return rowView;
}
public class ChildPagerAdapter extends FragmentStatePagerAdapter {
private List<ChildItemSample> pagerItemList;
private int items_per_page;
ChildPagerAdapter(FragmentManager fm, List<ChildItemSample> pagerItemList, int items_per_page) {
super(fm);
this.pagerItemList = pagerItemList;
this.items_per_page = items_per_page;
}
#Override
public Fragment getItem(int position) {
return ChildFragment.newInstance(position, pagerItemList, items_per_page);
}
#Override
public int getCount() {
int remainedItemCount = pagerItemList.size()%child_items_per_page;
if(remainedItemCount == 0)
return (pagerItemList.size()/child_items_per_page);
else
return (pagerItemList.size()/child_items_per_page + 1);
}
}
public static class ChildFragment extends Fragment {
private static final String SECTION_NUMBER = "section_number";
private static final String ITEMS_PER_PAGE = "items/page";
private static List<ChildItemSample> itemList;
public ChildFragment() {}
public static ChildFragment newInstance(int sectionNumber, List<ChildItemSample> pagerItemList,
int itemPerPage) {
ChildFragment fragment = new ChildFragment();
Bundle args = new Bundle();
args.putInt(SECTION_NUMBER, sectionNumber);
args.putInt(ITEMS_PER_PAGE, itemPerPage);
fragment.setArguments(args);
itemList = pagerItemList;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int child_items_per_page = getArguments().getInt(ITEMS_PER_PAGE);
int start_item = getArguments().getInt(SECTION_NUMBER)*child_items_per_page;
int itemCount = itemList.size() - getArguments().getInt(SECTION_NUMBER)*child_items_per_page;
if(itemCount > child_items_per_page) itemCount = child_items_per_page;
itemCount += getArguments().getInt(SECTION_NUMBER)*child_items_per_page;
GridLayout pageView = (GridLayout)inflater.inflate(R.layout.list_pager_item, container, false);
for(int i=start_item; i<itemCount; i++){
ChildItemSample expandedListText = itemList.get(i);
CheckBox cbChild = new CheckBox(getContext());
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = (int)(80 * getContext().getResources().getDisplayMetrics().density);
cbChild.setLayoutParams(params);
cbChild.setChecked(expandedListText.isChecked());
cbChild.setText(expandedListText.getName());
cbChild.setTag(i);
pageView.addView(cbChild);
cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
int pos = (int) view.getTag();
ChildItemSample selectedItem = itemList.get(pos);
selectedItem.setChecked(cb.isChecked());
if(cb.isChecked()){
checkedBoxesCount++;
Toast.makeText(getContext(),"Checked value is: " +
itemList.get(pos).getName(),
Toast.LENGTH_SHORT).show();
}else {
checkedBoxesCount--;
if(checkedBoxesCount == 0){
Toast.makeText(getContext(),"nothing checked",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getContext(),"unchecked",Toast.LENGTH_SHORT).show();
}
}
}
});
}
return pageView;
}
}
public void clearChecks() {
for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;
for(List<ChildItemSample> value : listChild.values()) {
for (ChildItemSample sample : value) {
sample.setChecked(false);
}
}
checkedBoxesCount = 0;
notifyDataSetChanged();
}
public ArrayList<String> getOrderList(){
ArrayList<String> overallOrder = new ArrayList<>();
for(int i=0; i<getGroupCount(); i++){
//for(int j=0; j<getChildrenCount(i); j++){
for(int j=0; j<listChild.get(getGroup(i)).size(); j++){
if(getChild(i,j).isChecked()){
String newOrder = getGroup(i) + ">" + getChild(i, j).getName();
overallOrder.add(newOrder);
}
}
}
return overallOrder;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class GroupViewHolder {
CheckBox cbGroup;
TextView tvGroup;
}
}
Another sample adapter that has ViewPager child (Without fragment)
public class ExpandableListPagerAdapter2 extends BaseExpandableListAdapter {
private Context context;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private int checkedBoxesCount;
private boolean[] checkedGroup;
private int child_items_per_page;
ExpandableListPagerAdapter2(Context context, List<String> listGroup, Map<String,
List<ChildItemSample>> listChild) {
this.context = context;
this.listGroup = listGroup;
this.listChild = listChild;
checkedBoxesCount = 0;
checkedGroup = new boolean[listGroup.size()];
child_items_per_page = context.getResources().getInteger(R.integer.pager_col_count) *
context.getResources().getInteger(R.integer.pager_row_count);
}
#Override
public int getGroupCount() {
return listGroup.size();
}
// ******* Special *******
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public String getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public ChildItemSample getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {
String itemGroup = getGroup(groupPosition);
GroupViewHolder groupViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_group, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);
groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);
groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
checkedGroup[pos] = !checkedGroup[pos];
for(ChildItemSample item : listChild.get(listGroup.get(pos))){
item.setChecked(checkedGroup[pos]);
}
notifyDataSetChanged();
}
});
view.setTag(groupViewHolder);
}else {
groupViewHolder = (GroupViewHolder)view.getTag();
}
groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, listChild.get(listGroup.get(groupPosition)).size()));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_child_pager, null);
ViewPager childLayout = rowView.findViewById(R.id.layout_child);
List<ChildItemSample> childItemSampleList = listChild.get(listGroup.get(groupPosition));
ChildPagerAdapter adapter = new ChildPagerAdapter(childItemSampleList);
childLayout.setAdapter(adapter);
return rowView;
}
public class ChildPagerAdapter extends PagerAdapter {
private List<ChildItemSample> pagerItemList;
ChildPagerAdapter(List<ChildItemSample> pagerItemList) {
this.pagerItemList = pagerItemList;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
int start_item = position*child_items_per_page;
int itemCount = pagerItemList.size() - start_item;
if(itemCount > child_items_per_page) itemCount = child_items_per_page;
itemCount += start_item;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
GridLayout pageView = (GridLayout)inflater.inflate(R.layout.list_pager_item, container, false);
for(int i=start_item; i<itemCount; i++){
ChildItemSample expandedListText = pagerItemList.get(i);
CheckBox cbChild = new CheckBox(context);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = (int)(80 * context.getResources().getDisplayMetrics().density);
cbChild.setLayoutParams(params);
cbChild.setChecked(expandedListText.isChecked());
cbChild.setText(expandedListText.getName() + "(" + expandedListText.getQty() + ")");
cbChild.setTag(i);
pageView.addView(cbChild);
cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int) view.getTag();
final ChildItemSample selectedItem = pagerItemList.get(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(selectedItem.getName());
final EditText editText = new EditText(context);
editText.setText("");
editText.append(String.valueOf(selectedItem.getQty()));
builder.setView(editText);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
selectedItem.setQty(Integer.parseInt(editText.getText().toString()));
ExpandableListPagerAdapter2.this.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", null);;
builder.show();
editText.requestFocus();
editText.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager keyboard = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editText, 0);
}
},200);
}
});
}
container.addView(pageView);
return pageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
int remainedItemCount = pagerItemList.size()%child_items_per_page;
if(remainedItemCount == 0)
return (pagerItemList.size()/child_items_per_page);
else
return (pagerItemList.size()/child_items_per_page + 1);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
public void clearChecks() {
for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;
for(List<ChildItemSample> value : listChild.values()) {
for (ChildItemSample sample : value) {
sample.setChecked(false);
}
}
checkedBoxesCount = 0;
notifyDataSetChanged();
}
public ArrayList<ChildItemSample> getOrderList(){
ArrayList<ChildItemSample> overallOrder = new ArrayList<>();
for(int i=0; i<getGroupCount(); i++){
for(int j=0; j<listChild.get(getGroup(i)).size(); j++){
if(getChild(i,j).getQty() > 0){
ChildItemSample newOrder = new ChildItemSample(getGroup(i) + ">" +
getChild(i, j).getName(), getChild(i, j).getQty());
overallOrder.add(newOrder);
}
}
}
return overallOrder;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class GroupViewHolder {
CheckBox cbGroup;
TextView tvGroup;
}
}

android listview, edittext same ID

I got a listView in a fragment. This listView use an BaseExpandableListAdapter. I got a list of question and for each of them, I have a list of answer. I add a Edittext after each last answer == last child (to add a new answer).
My problem is that each edittext has the same ID, so when I have more than one question, I can't write inside the edittext because two edittext have the same Id.
I don't know how to manage it :'(.
-> Fragment code :
public class HomeFragment extends Fragment implements AbsListView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private AdapterHomeFragment adapter;
private LinkedList<Question> listQuestion;
private ExpandableListView listView;
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
listQuestion = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
listView = (ExpandableListView) rootView.findViewById(R.id.listView);
adapter = new AdapterHomeFragment(getActivity(), listQuestion);
listView.setAdapter(adapter);
listView.setGroupIndicator(null);
return rootView;
}
/*
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
*/
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
public void refreshData()
{
listQuestion = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
adapter = new AdapterHomeFragment(getActivity(), listQuestion);
listView.setAdapter(adapter);
listView.setGroupIndicator(null);
}
-> Adapter code :
public class AdapterHomeFragment extends BaseExpandableListAdapter {
private LinkedList<Question> groups;
public LayoutInflater inflater;
public Activity activity;
public AdapterHomeFragment(Activity act, LinkedList<Question> groups) {
activity = act;
this.groups = groups;
inflater = act.getLayoutInflater();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return groups.get(groupPosition).getListAnswer().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (!isLastChild) {
Answer answer = (Answer) getChild(groupPosition, childPosition);
TextView text = null;
convertView = inflater.inflate(R.layout.rowanswer_home, null);
text = (TextView) convertView.findViewById(R.id.rowanswer_home_answer);
text.setText(answer.getAnswer());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_author);
text.setText("Anonymous"+answer.getUserId().toString());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_time);
text.setText(answer.getDifferenceTime()+" ago");
}
else
{
TextView text = null;
convertView = inflater.inflate(R.layout.footer_answer, null);
final Question question = groups.get(groupPosition);
final EditText editText = (EditText)convertView.findViewById(R.id.footer_answer_edit_text);
final Button button = (Button) convertView.findViewById(R.id.footer_answer_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text_answer = editText.getText().toString();
QuestionManager.getQuestionManager().addAnswer(text_answer, question.getId());
groups = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
notifyDataSetChanged();
}
});
button.setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
String text = editText.getText().toString();
if (verifyFormatString(text)) {
button.setEnabled(true);
} else
button.setEnabled(false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Log.d("test5780", String.valueOf(editText.getId()));
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return groups.get(groupPosition).getListAnswer().size() + 1;
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
int nbAnswer;
if (convertView == null) {
convertView = inflater.inflate(R.layout.rowquestion_home, null);
}
Question question = (Question) getGroup(groupPosition);
((CheckedTextView) convertView.findViewById(R.id.rowquestion_home_question)).setText(question.getQuestion());
((CheckedTextView) convertView.findViewById(R.id.rowquestion_home_question)).setChecked(isExpanded);
((TextView) convertView.findViewById(R.id.rowquestion_home_author)).setText("Anonymous" + question.getUserId().toString());
((TextView) convertView.findViewById(R.id.rowquestion_home_time)).setText(question.getDifferenceTime()+ " ago");
nbAnswer = question.getListAnswer().size();
if (nbAnswer == 1)
((TextView) convertView.findViewById(R.id.rowquestion_home_nbAnswer)).setText(String.valueOf(question.getListAnswer().size()) + " answer");
else
((TextView) convertView.findViewById(R.id.rowquestion_home_nbAnswer)).setText(String.valueOf(question.getListAnswer().size()) + " answers");
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean verifyFormatString (String question)
{
boolean valid = false;
int i = 0;
while (!valid && i < question.length())
{
if (question.charAt(i) != ' ')
valid = true;
i += 1;
}
return valid;
}
-> Xml of the footer
<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="40dp"
android:clickable="true"
android:orientation="vertical"
android:paddingLeft="40dp"
android:background="#color/layout_button"
tools:context=".MainActivity" >
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/footer_answer_block"
/>
<EditText
android:id="#+id/footer_answer_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawablePadding="5dp"
android:gravity="center_vertical"
android:hint="Add answer"
android:textSize="14sp"
android:textStyle="italic"
android:layout_toLeftOf="#+id/footer_answer_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</EditText>
<Button
android:id="#+id/footer_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="1"
android:textSize="12sp"
android:text="add"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/footer_answer_block">
</Button>
If you have any idea how to resolve it, it will help me a lot !
Thank you.
When I click on the edittext the keyboard open but instant lose the focus on the edittext and it's impossible to write inside
You can use setTag() method of view. So whenever your getChildView() executes just set editText.setTag(position). Once user submit the answer you just need to find the tag that in which edit test user has typed by edittext.getTag(). It will return you the position which you tagged at the time of getChildView() execution. By that way you can get to know different answers once you have more than 1 question.
getChildView() Code
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (!isLastChild) {
Answer answer = (Answer) getChild(groupPosition, childPosition);
TextView text = null;
convertView = inflater.inflate(R.layout.rowanswer_home, null);
text = (TextView) convertView.findViewById(R.id.rowanswer_home_answer);
text.setText(answer.getAnswer());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_author);
text.setText("Anonymous"+answer.getUserId().toString());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_time);
text.setText(answer.getDifferenceTime()+" ago");
}
else
{
TextView text = null;
convertView = inflater.inflate(R.layout.footer_answer, null);
final Question question = groups.get(groupPosition);
final EditText editText = (EditText)convertView.findViewById(R.id.footer_answer_edit_text);
editText.setTag(childPosition);
final Button button = (Button) convertView.findViewById(R.id.footer_answer_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text_answer = editText.getText().toString();
QuestionManager.getQuestionManager().addAnswer(text_answer, question.getId());
groups = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
notifyDataSetChanged();
}
});
button.setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
String text = editText.getText().toString();
int answeredPosition = (Integer)editText.getTag();
Log.d("Answered Position",""+answeredPosition);// This is the position of question in listview for which user has typed the answer.
if (verifyFormatString(text)) {
button.setEnabled(true);
} else
button.setEnabled(false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Log.d("test5780", String.valueOf(editText.getId()));
}
return convertView;
}
Let me know if it work or you need more descriptive answer.

ExpandableListView - getChildAt() returns the wrong View

So I have this ExpandableListView that should highlight the groups that are clicked.
I do this by running
eList.getChildAt(eList.getFlatListPosition(ExpandableListView.getPackedPositionForGroup(i))).setBackgroundColor(Color.LTGRAY);
whereas i is the index of the group's view that was clicked.
However, as you can see in the image provided here, it only returns the correct view when I'm traversing upwards the list.
http://i.imgur.com/I9e943A.gif
I should note that when I have the onGroupClick() set to return false, getChildAt returns the correct value and the correct group view is highlighted. However, having it set to false would result in groups opening twice when clicked(twice as many child elements), as I'm "manually" collapsing/expanding the groups as the /searchterm/ changes.
For debugging purposes I tried to highlight the getChildAt(1) when any group was clicked. The "1" group was highlighted in all cases except for when I clicked the "0" group, whereas the last group was highlighted instead.
Classes can be found below
MainActivity:
public class MainActivity extends ActionBarActivity {
HashMap<String, List<String>> categoryName;
List<String> categoryList;
ExpandableListView eList;
CategoryAdapter adapter;
EditText textField;
int lastHighlightParent = -1;
int lastHighlightChild = -1;
int groupToHighlight;
String prevDirName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Laboration 2");
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.etTextField);
textField.setText("€/€");
eList = (ExpandableListView) findViewById(R.id.exp_list);
textField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (lastHighlightChild != -1 && lastHighlightParent != -1) {
eList.getChildAt(
eList.getFlatListPosition(ExpandableListView
.getPackedPositionForChild(
lastHighlightParent,
lastHighlightChild)))
.setBackgroundColor(Color.TRANSPARENT);
lastHighlightChild = -1;
lastHighlightParent = -1;
}
for (int i = 0; i < eList.getChildCount(); i++) {
eList.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
boolean match = false;
for (int i = 0; i < adapter.getGroupCount(); i++) {
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
String tempPath = "/" + adapter.getGroupText(i) + "/"
+ adapter.getChildText(i, j);
if (tempPath.startsWith(s.toString())
&& s.toString().length() > 1 && match != true) {
groupToHighlight = eList.getFlatListPosition(ExpandableListView
.getPackedPositionForGroup(i));
eList.getChildAt(eList.getFlatListPosition(ExpandableListView
.getPackedPositionForGroup(i))).setBackgroundColor(Color.LTGRAY);
textField.setBackgroundColor(Color.TRANSPARENT);
match = true;
} else if (s.toString().equals("/") || s.length() == 0) {
textField.setBackgroundColor(Color.TRANSPARENT);
} else {
if (match != true) {
eList.getChildAt(i).setBackgroundColor(
Color.TRANSPARENT);
textField.setBackgroundColor(Color.RED);
}
}
}
}
for (int i = 0; i < adapter.getGroupCount(); i++) {
if (s.toString().startsWith(
"/" + adapter.getGroupText(i) + "/")) {
if (!eList.isGroupExpanded(i)) {
eList.expandGroup(i);
}
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
if (s.toString().endsWith(
adapter.getChildText(i, j))) {
eList.getChildAt(
eList.getFlatListPosition(ExpandableListView
.getPackedPositionForChild(i, j)))
.setBackgroundColor(Color.GRAY);
lastHighlightParent = i;
lastHighlightChild = j;
}
}
} else {
eList.collapseGroup(i);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
eList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
textField.setText("/" + adapter.getGroupText(groupPosition)
+ "/"
+ adapter.getChildText(groupPosition, childPosition));
return false;
}
});
eList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
if (adapter.getGroupText(groupPosition).equals(prevDirName)
&& eList.isGroupExpanded(groupPosition)) {
eList.collapseGroup(groupPosition);
} else {
textField.setText("/" + adapter.getGroupText(groupPosition)
+ "/");
}
prevDirName = adapter.getGroupText(groupPosition);
return true;
}
});
categoryName = listData();
categoryList = new ArrayList<String>(categoryName.keySet());
adapter = new CategoryAdapter(this, categoryName, categoryList);
eList.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private HashMap<String, List<String>> listData() {
HashMap<String, List<String>> categoryDetail = new HashMap<String, List<String>>();
List<String> drinks = new ArrayList<String>();
drinks.add("Tea");
drinks.add("Coffee");
drinks.add("Water");
drinks.add("Lemonade");
drinks.add("Beer");
List<String> animals = new ArrayList<String>();
animals.add("Cat");
animals.add("Dog");
animals.add("Dromedary");
animals.add("Boar");
List<String> vegetables = new ArrayList<String>();
vegetables.add("Lettuce");
vegetables.add("Tomato");
vegetables.add("Spinach");
vegetables.add("Cucumber");
List<String> colors = new ArrayList<String>();
colors.add("Blue");
colors.add("Red");
colors.add("Pink");
colors.add("Brown");
List<String> sodas = new ArrayList<String>();
sodas.add("Cola");
sodas.add("Pepsi");
sodas.add("Fanta");
sodas.add("7-up");
categoryDetail.put("Animals", animals);
categoryDetail.put("Vegetables", vegetables);
categoryDetail.put("Colors", colors);
categoryDetail.put("Sodas", sodas);
categoryDetail.put("Drinks", drinks);
return categoryDetail;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
textField.setText(item.getTitle());
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter:
public class CategoryAdapter extends BaseExpandableListAdapter {
private Context context;
private HashMap<String, List<String>> categories;
private List<String> categoryList;
public CategoryAdapter(Context m_context, HashMap<String, List<String>> m_categories, List<String> m_categoryList){
this.context = m_context;
this.categories = m_categories;
this.categoryList = m_categoryList;
}
public String getGroupText(int groupPosition){
Object[] keys = this.categories.keySet().toArray();
return (String) keys[groupPosition];
}
public String getChildText(int groupPosition, int childPosition){
Object[] keys = this.categories.keySet().toArray();
return (String) categories.get(keys[groupPosition]).get(childPosition);
}
#Override
public int getGroupCount() {
return categoryList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return categories.get(categoryList.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return categoryList.get(groupPosition);
}
#Override
public Object getChild(int parent, int child) {
return categories.get(categoryList.get(parent)).get(child);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int parent, int child){
return child;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int parent, boolean isExpanded,
View convertView, ViewGroup parentView) {
String groupTitle = (String) getGroup(parent);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.parent_layout, parentView, false);
}
TextView parentTextView = (TextView) convertView.findViewById(R.id.parent_txt);
parentTextView.setTypeface(null, Typeface.BOLD);
parentTextView.setText(groupTitle);
return convertView;
}
#Override
public View getChildView(int parent, int child,
boolean isLastChild, View convertView, ViewGroup parentView) {
String childTitle = (String) getChild(parent, child);
if (convertView == null) {
LayoutInflater inflat = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflat.inflate(R.layout.child_layout, parentView, false);
}
TextView childTextView = (TextView) convertView.findViewById(R.id.child_txt);
childTextView.setText(childTitle);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}

Override default expandablelistview expand behaviour

How does one go about manually expanding and collapsing an expandablelistview? I know of expandGroup(), but am not sure where to set the onClickListener(), as half of this code, is in a separate library project.
ExpandableDeliveryList
package com.goosesys.dta_pta_test;
[imports removed to save space]
public class ExpandableDeliveryList<T> extends ExpandableListActivity {
private ArrayList<GooseDeliveryItem> parentItems = new ArrayList<GooseDeliveryItem>();
private ArrayList<DeliverySiteExtras> childItems = new ArrayList<DeliverySiteExtras>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// CREATE THE EXPANDABLE LIST AND SET PROPERTIES //
final ExpandableListView expandList = getExpandableListView();
expandList.setDividerHeight(0);
expandList.setGroupIndicator(null);
expandList.setClickable(false);
// LIST OF PARENTS //
setGroupParents();
// CHILDREN //
setChildData();
// CREATE ADAPTER //
GooseExpandableArrayAdapter<?> adapter = new GooseExpandableArrayAdapter<Object>(
R.layout.goose_delivery_item,
R.layout.goose_delivery_item_child,
parentItems,
childItems);
adapter.setInflater((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
expandList.setAdapter(adapter);
expandList.setOnChildClickListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case android.R.id.home:
{
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
}
default:
{
return super.onOptionsItemSelected(item);
}
}
}
public void setGroupParents()
{
DatabaseHelper dbHelper = new DatabaseHelper(this);
List<DeliverySite> sites = new ArrayList<DeliverySite>();
sites = dbHelper.getAllSites();
GooseDeliveryItem[] deliveries = new GooseDeliveryItem[sites.size()];
for(int i=0; i<sites.size(); i++)
{
Delivery del = new Delivery();
try
{
del = dbHelper.getDeliveryByJobNo(sites.get(i).id);
}
catch(Exception e)
{
e.printStackTrace();
}
final GooseDeliveryItem gdi;
if((Double.isNaN(sites.get(i).lat)) || (Double.isNaN(sites.get(i).lng)))
{
gdi = new GooseDeliveryItem(sites.get(i).id, sites.get(i).company);
}
else
{
gdi = new GooseDeliveryItem(sites.get(i).id, sites.get(i).company, sites.get(i).lat, sites.get(i).lng);
}
if(del.getReportedFully() == 1)
{
gdi.isReportedFully = true;
}
deliveries[i] = gdi;
}
// FINALLY ADD THESE ITEMS TO THE PARENT ITEMS LIST ARRAY //
for(GooseDeliveryItem g : deliveries)
parentItems.add(g);
}
public void setChildData()
{
//DatabaseHelper dbHelper = new DatabaseHelper(this);
ArrayList<DeliverySiteExtras> extras = new ArrayList<DeliverySiteExtras>();
for(int i=0; i<parentItems.size(); i++)
{
DeliverySiteExtras dse = new DeliverySiteExtras();
extras.add(dse);
}
childItems = extras;
}
}
ArrayAdapter
package com.goosesys.gooselib.Views;
[imports removed to save space]
public class GooseExpandableArrayAdapter<Object> extends BaseExpandableListAdapter
{
private Activity activity;
private ArrayList<DeliverySiteExtras> childItems;
private LayoutInflater inflater;
ArrayList<GooseDeliveryItem> parentItems;
private DeliverySiteExtras child;
private int layoutId;
private int childLayoutId;
public GooseExpandableArrayAdapter(int layoutId, int childLayoutId, ArrayList<GooseDeliveryItem> parents, ArrayList<DeliverySiteExtras> children)
{
this.layoutId = layoutId;
this.childLayoutId = childLayoutId;
this.parentItems = (ArrayList<GooseDeliveryItem>) parents;
this.childItems = (ArrayList<DeliverySiteExtras>)children;
}
public GooseExpandableArrayAdapter(ArrayList<GooseDeliveryItem> parents, ArrayList<DeliverySiteExtras> children, int layoutId)
{
this.parentItems = parents;
this.childItems = children;
this.layoutId = layoutId;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
#Override
public Object getChild(int arg0, int arg1)
{
return null;
}
#Override
public long getChildId(int arg0, int arg1)
{
return 0;
}
/*
* Child view get method
* Utilise this to edit view properties at run time
*/
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = childItems.get(groupPosition);
if(convertView == null)
{
convertView = inflater.inflate(this.childLayoutId, null);
}
// GET ALL THE OBJECT VIEWS AND SET THEM HERE //
setGeoLocation(groupPosition, convertView);
convertView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
}
});
return convertView;
}
#Override
public void onGroupCollapsed(int groupPosition)
{
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition)
{
super.onGroupExpanded(groupPosition);
}
#Override
public int getChildrenCount(int groupPosition)
{
return 1; //childItems.get(groupPosition);
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.size();
}
#Override
public long getGroupId(int arg0)
{
return 0;
}
/*
* Parent View Object get method
* Utilise this to edit view properties at run time.
*/
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = inflater.inflate(this.layoutId, null);
}
// GET ALL OBJECT VIEWS AND SET THEM HERE -- PARENT VIEW //
TextView name = (TextView)convertView.findViewById(R.id.customerName);
name.setText(parentItems.get(groupPosition).customerText);
ImageView go = (ImageView)convertView.findViewById(R.id.moreDetails);
go.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(activity, DeliveryJobActivity.class);
i.putExtra("obj", parentItems.get(groupPosition));
activity.startActivity(i);
}
});
return convertView;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int arg0, int arg1)
{
return false;
}
private void setGeoLocation(final int groupPosition, View parent)
{
GeoLocation geoLocation = new GeoLocation(activity);
final double lat = geoLocation.getLatitude();
final double lng = geoLocation.getLongitude();
// GET OUR START LOCATION //
Location startLocation = new Location("Start");
startLocation.setLatitude(lat);
startLocation.setLongitude(lng);
// GET OUR DESTINATION //
Location destination = new Location("End");
destination.setLatitude(((GooseDeliveryItem)parentItems.get(groupPosition)).latitude);
destination.setLongitude(((GooseDeliveryItem)parentItems.get(groupPosition)).longitude);
double distanceValue = startLocation.distanceTo(destination);
TextView tv = (TextView)parent.findViewById(R.id.extraHeader);
tv.setText(parentItems.get(groupPosition).customerText + " information:");
TextView ds = (TextView)parent.findViewById(R.id.deliveryDistance);
ds.setText("Distance (from location): " + String.valueOf(Math.ceil(distanceValue * GooseConsts.METERS_TO_A_MILE)) + " Mi (approx)");
ImageView img = (ImageView)parent.findViewById(R.id.directionsImage);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// invoke google maps with lat / lng position
Intent navigation = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://maps.google.com/maps?saddr="
+ (lat) + "," + (lng)
+ "&daddr="
+ ((GooseDeliveryItem)parentItems.get(groupPosition)).latitude + ","
+ ((GooseDeliveryItem)parentItems.get(groupPosition)).longitude
));
activity.startActivity(navigation);
}
});
}
}
Ideally, my bosses would like to have a "+" button, that when clicked expands the listview manually. Rather than clicking anywhere on the view and it doing it automatically. Is this possible? Also, setting setClickable(false) seems to have no effect. Because it'll still expand when any list item is clicked. Am I missing something there also?
Cheers.
You can add an ExpandableListView Group Click Listener ("ExpandableListView::setOnGroupClickListener") to monitor and suppress click event for the ListView Groups. Using your code example, this would be done in your "ExpandableDeliveryList" module after you create the ExpandableListView.
Then in your "+" (and "-") Button click handlers, you can add logic to expand/collapse some or all of the ListView Groups using the "ExpandableListView::expandGroup()" and "ExpandableListView::collapseGroup()" methods.
You do not need to return "false" from the overridden "isChildSelectable()" method as this has no effect on what you are trying to accomplish (and will prevent anyone from clicking/selecting child items in the ListView).
Code examples are shown below:
// CREATE THE EXPANDABLE LIST AND SET PROPERTIES //
final ExpandableListView expandList = getExpandableListView();
//...
expandList.setOnGroupClickListener(new android.widget.ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick( ExpandableListView parent,
View view,
int groupPosition,
long id) {
// some code...
// return "true" to consume the event (and prevent the Group from expanding/collapsing) / "false" to allow the Group to expand/collapse normally
return true;
}
});
To manually expand and collapse the ListView Groups:
// enumerate thru the ExpandableListView Groups
// [in this code example, a single index is used...]
int groupPosition = 0;
// expand the ListView Group/s
if (m_expandableListView.isGroupExpanded(groupPosition) == false) {
// API Level 14+ allows you to animate the Group expansion...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
m_expandableListView.expandGroup(groupPosition, true);
}
// else just expand the Group without animation
else {
m_expandableListView.expandGroup(groupPosition);
}
}
// collapse the ListView Group/s
else {
m_expandableListView.collapseGroup(groupPosition);
}
Hope this Helps.

Categories

Resources