I have created a navigation drawer with an expandable listview inside it. I want the expandable listview to expand one of its groups and select one of its child by default when the activity opens up. The user may change the selection according to his requirement.
Whatever I have created is not satisfying my requirement. The expandable list is allowing the user to select multiple options.
The MainActivity:
public class MainActivity extends Activity {
DrawerLayout mDrawerLayout;
ExpandableListView mDrawerList;
ExpandableListAdapter listAdapter;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ActionBar mActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Action bar with collapse icon for drawer menu===================
mActionBar = getActionBar();
mActionBar.setHomeButtonEnabled(true);
mActionBar.setDisplayHomeAsUpEnabled(false);
// Action bar with collapse icon for drawer menu===================
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
mDrawerList.setAdapter(listAdapter);
// Listview Group click listener
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// // Listview Group expanded listener
// mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
//
// #Override
// public void onGroupExpand(int groupPosition) {
// Toast.makeText(getApplicationContext(),
// listDataHeader.get(groupPosition) + " Expanded",
// Toast.LENGTH_SHORT).show();
// }
// });
//
// // Listview Group collasped listener
// mDrawerList.setOnGroupCollapseListener(new OnGroupCollapseListener()
// {
//
// #Override
// public void onGroupCollapse(int groupPosition) {
// Toast.makeText(getApplicationContext(),
// listDataHeader.get(groupPosition) + " Collapsed",
// Toast.LENGTH_SHORT).show();
//
// }
// });
// mDrawerList.expandGroup(2);
// mDrawerList.expandGroup(2, true);
// Listview on child click listener
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
// TODO Auto-generated method stub
// Toast.makeText(
// getApplicationContext(),
// listDataHeader.get(groupPosition)
// + " : "
// + listDataChild.get(
// listDataHeader.get(groupPosition)).get(
// childPosition), Toast.LENGTH_SHORT)
// .show();
v.setBackgroundColor(Color.BLUE);
makeAToast("Group: " + groupPosition + " Child: "
+ childPosition);
return false;
}
});
// To collapse previously opened group===========
mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
int previousItem = -1;
#Override
public void onGroupExpand(int groupPosition) {
if (groupPosition != previousItem)
mDrawerList.collapseGroup(previousItem);
previousItem = groupPosition;
}
});
// To collapse previously opened group===========
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding header data
listDataHeader.add("Today");
// Adding child data
List<String> today = new ArrayList<String>();
today.add("Tanushree Guha");
today.add("Prasenjit Roy");
today.add("Pan Singh Tomar");
today.add("Milka Singh");
today.add("Rohit Ramanujan");
today.add("Ramesh Bhatt");
today.add("Debjani Brahma");
listDataHeader.add("Tomorrow");
List<String> tomorrow = new ArrayList<String>();
tomorrow.add("Dipanjan Bhowmik");
tomorrow.add("Sarmistha Sinha");
tomorrow.add("Pranay Lalwani");
tomorrow.add("Mohit Shaw");
tomorrow.add("Lovelace Agarwal");
tomorrow.add("Tanmay Banerjee");
listDataHeader.add("Later");
List<String> later = new ArrayList<String>();
later.add("Yusuf Khan");
later.add("Jitendar Sharma");
later.add("Debashree Roy");
later.add("Mainak Ghosh");
later.add("Olivia Gomes");
listDataChild.put(listDataHeader.get(0), today); // Header, Child data
listDataChild.put(listDataHeader.get(1), tomorrow);
listDataChild.put(listDataHeader.get(2), later);
}
// method to show toast message
public void makeAToast(String str) {
Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
The activity_main.xml layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ExpandableListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#999999"
android:dividerHeight="1dp"
android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
The ExpandableListAdapter class:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
If anymore source code is required, I will provide it. What should I do to satisfy my requirement?
For the first part of the question:
I want the expandable listview to expand one of its groups and select
one of its child by default when the activity opens up
mExpandableListView.setSelectedChild(groupPosition, childPosition, shouldExpandGroup);
where :
groupPosition is the position of the group that should be expanded first
position of the child that should be selected by default *More info below
shouldExpandGroup is a boolean that should be set to true to expand the group
Info for 2 above.
Maintain a hashmap containing the group postion and the child position selected by the user like:
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(groupPosition, childPosition);
For every child selection simply put it into the hashmap, it would overwrite the value if present
Store this hashmap either in a file or somewhere where you can access it again (may be shared preference but it does not allow storage of objects)
When the activity starts get the value from the hashmap, and set the selection,
you could set the selection for all the groups but with shouldExpand to false for all
except the first. If the map is empty set default selection to 0.
I would recomment using SlideExpandableListView for Android:
(Well that screenshot is crap but you can guess the animation)
This is the official description of that library:
Not happy with the Android ExpandableListView android offers? Want something like the Spotify app. This library allows you to have custom listview in wich each list item has an area that will slide-out once the users clicks on a certain button.
Features
Provides a better ExpandableListView usable for normal ListView's
Animates by default
Easy to use
Check that repository at GitHub: https://github.com/tjerkw/Android-SlideExpandableListView/.
Related
I am working on my expandablelistview menu that when I click on the menu item, I want to set the menu item to bold while set the other menu item to normal textype.
ExpandableListAdapter:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private HashMap<String, String> imgnamedata;
private boolean hasChild = false;
private int selectedItem;
public ExpandableListAdapter(MainActivity context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild, HashMap<String, String> img_data) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listDataChild;
this.imgnamedata = img_data;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(
this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public boolean isHasChild (boolean hasChild) {
return hasChild;
}
public void selectItem(int selectedItem){
this.selectedItem = selectedItem;
notifyDataSetChanged();
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition,
childPosition);
//final HeaderModel header = (HeaderModel) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item1, null);
}
final TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
//txtListChild.setTypeface(null, Typeface.NORMAL);
txtListChild.setText(childText);
txtListChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isChildSelectable = true;
txtListChild.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
}
});
return convertView;
}
private boolean isHasChild() {
return hasChild;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(
this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
int c_size = getChildrenCount(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
// changing the +/- on expanded list view
// this is the +/- text view that act as image.
// on expand this change to - and on close it again change to +
ImageView txt_plusminus = (ImageView) convertView
.findViewById(R.id.plus_txt);
if (c_size > 0) {
txt_plusminus.setVisibility(View.VISIBLE);
if (isExpanded) {
txt_plusminus.setImageDrawable(this._context.getResources().getDrawable(R.drawable.downarrow));
} else {
txt_plusminus.setImageDrawable(this._context.getResources().getDrawable(R.drawable.rightarrow));
}
} else {
txt_plusminus.setVisibility(View.GONE);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
// lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
lblListHeader.setTypeface(null, Typeface.BOLD);
// Either you can use this below for setting icon in main menu:
// adding icon to expandable list view
ImageView imgListGroup = (ImageView) convertView
.findViewById(R.id.ic_txt);
String icn = this.imgnamedata.get(headerTitle);
if (icn != null) {
String uri = "#drawable/" + icn;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = null;
try {
res = getResources().getDrawable(imageResource);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
if (res != null) {
imgListGroup.setImageDrawable(res);
} else {
imgListGroup.setImageResource(R.drawable.ic_launcher_background);
}
} else {
imgListGroup.setImageResource(R.drawable.ic_launcher_background);
}
return convertView;
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ExpandableListView interface1,if_list,adons_list,ss_list,tool_list;
ImageView close_d;
Toolbar toolbar;
WebView webview;
TextView lblListHeader;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
RelativeLayout drawer_relative, interface1_test;
private boolean isSelected = false;
private boolean isChildSelectable = false;
private String selectedText = null;
private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener() {
#Override
public void onDrawerStateChanged(int status) {
}
#Override
public void onDrawerSlide(View view, float slideArg) {
}
#Override
public void onDrawerOpened(View view) {
// toolbar.setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View view) {
// toolbar.setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
// invalidateOptionsMenu();
}
};
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
close_d = findViewById(R.id.close_d);
drawer_relative = findViewById(R.id.drawer_relative);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerListener);
interface1 = (ExpandableListView) findViewById(R.id.interface1);
if_list = (ExpandableListView) findViewById(R.id.if_list);
adons_list = (ExpandableListView) findViewById(R.id.adons_list);
ss_list = (ExpandableListView) findViewById(R.id.ss_list);
tool_list = (ExpandableListView) findViewById(R.id.tool_list);
lblListHeader = (TextView) findViewById(com.dvinfosys.R.id.lblListHeader);
webview = (WebView) findViewById(R.id.webview);
isSelected = false;
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
// toolbar.setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
// invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
// toolbar.setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
ArrayList dashbord_listDataHeader = new ArrayList<String>();
HashMap<String, List<String>> dashbord_listDataChild = new HashMap<String, List<String>>();
HashMap<String, String> img_data = new HashMap<>();
dashbord_listDataHeader.add("Dashboard");
dashbord_listDataChild.put("Dashboard",new ArrayList<String>());
img_data.put("Dashboard","dashboard");
ExpandableListAdapter listAdapter = new ExpandableListAdapter(MainActivity.this, dashbord_listDataHeader,
dashbord_listDataChild,img_data);
interface1.setAdapter(listAdapter);
interface1.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
selectedText = "Dashboard";
TextView dashboard = v.findViewById(R.id.lblListHeader);
dashboard.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
return false;
}
});
HashMap<String, String> img_data1 = new HashMap<>();
HashMap<String, List<String>> interface_listDataChild = new HashMap<String, List<String>>();
ArrayList interface_listDataHeader = new ArrayList<String>();
List<String> sub_data = new ArrayList<>();
List<String> sub_data1 = new ArrayList<>();
interface_listDataHeader.add("Contacts");
interface_listDataHeader.add("Newsletters");
sub_data.add("Search Contacts");
sub_data.add("Add Contacts");
sub_data.add("Import Contacts");
sub_data1.add("Create Newsletter");
sub_data1.add("My Newsletters");
interface_listDataChild.put("Contacts", sub_data);
interface_listDataChild.put("Newsletters", sub_data1);
img_data1.put("Contacts","contacts");
img_data1.put("Newsletters","newsletter");
ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(MainActivity.this, interface_listDataHeader,
interface_listDataChild,img_data1);
if_list.setAdapter(listAdapter1);
if_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
return false;
}
});
ArrayList addons_listDataHeader = new ArrayList<String>();
HashMap<String, String> img_data2 = new HashMap<>();
HashMap<String, List<String>> addons_listDataChild = new HashMap<String, List<String>>();
List<String> sub_data2 = new ArrayList<>();
addons_listDataHeader.add("Autoresponder");
addons_listDataHeader.add("My Campaign");
addons_listDataHeader.add("Split Tests");
sub_data2.add("Create Autoresponder");
sub_data2.add("My Autoresponder");
addons_listDataChild.put("Autoresponder", sub_data2);
addons_listDataChild.put("My Campaign",new ArrayList<String>());
addons_listDataChild.put("Split Tests",new ArrayList<String>());
img_data2.put("Autoresponder","autoresponder");
img_data2.put("My Campaign","campaign");
img_data2.put("Split Tests","splittest");
ExpandableListAdapter listAdapter2 = new ExpandableListAdapter(MainActivity.this, addons_listDataHeader,
addons_listDataChild,img_data2);
adons_list.setAdapter(listAdapter2);
adons_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
TextView addon_header = v.findViewById(R.id.lblListHeader);
if (id == 1) {
selectedText = "Campaign";
}
else if (id == 2) {
selectedText = "Split Tests";
}
addon_header.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
return false;
}
});
}
When I click on the menu item, example: My Newsletter. The menu item "Dashboard" have a bold so I want to set the "Dashboard" to normal typetext and set the menu item "My Newsletter" to bold typetext. And when I click menu item "Create Newsletter", I want to set the the "My Newsletter" to normal typetext and set the menu item "Create Newsletter" to bold.
On my code, what it will do that it will set the menu item to bold when I click on the menu item but it wont set the other menu item to normal.
Can you please show me an example how I could do that using with my code?
EDIT: I have tried this:
ss_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
TextView ss_header = v.findViewById(R.id.lblListHeader);
ss_header.setTypeface(null, Typeface.NORMAL);
if (id == 0) {
//do something
}
else if (id == 1) {
//do something
}
ss_header.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
return false;
}
});`
you can try this for changing the text style
button/textView.setTypeface(Typeface.DEFAULT_BOLD/NORMAL);
and on each button press, set the text as you wish.
I hope it could help
My design : I have created a custom adapter(SignalsExpandableListAdapter)with a CheckedTextView for my ExpandableListView.
public class SignalsExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHandler;
private HashMap<String,List<String>> listHashMap;
public SignalsExpandableListAdapter(Context context, List<String> listDataHandler, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHandler = listDataHandler;
this.listHashMap = listHashMap;
}
Then data is filled inside a fragment with HashMap and List as below. This works well. I can see children and parent elements inside my ExpandableListView.
ArrayList<List<String[]>> deviceMList = new ArrayList<>();
final List<String[]> mList = new ArrayList<>();
deviceMList.add(mList);
What I'm looking for I : When I select any child (can be multiple) I want to indicate that selection with a tick using CheckedTextView. And also I want to uncheck when I select any checked child item. (A simple check/uncheck design ). As well when any child is selected another function is called for plotting. This is where I got stuck. Every time when I select one child, random multiple children checkedTextViews are also indicated as checked not only the one I select.
After some searching I tried 3 attempts to overcome this and to check only the child I select. But it seems like neither of my attempts is working. I'm not sure what is going on. My attempts are mentioned below. I would really appreciate any suggestions on this.
I tried Attempt 4 (Described below in section II.) but still seems like check/unchecks is not happening in real-time.
Attempt 1 : Trying to make checked true inside Fragment
listAdapter = new SignalsExpandableListAdapter(context,signalsListDataHeader,signalsListHash);
signalsExpandableListView.setAdapter(listAdapter);
signalsExpandableListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
//tickCheckboxes();
signalsExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
CheckedTextView sensorCheckedView = (CheckedTextView) v.findViewById(R.id.sensorsCheckedTextView);
if(!mService.mPlotManager.ifPropertyExist(deviceMList.get(groupPosition).get(childPosition))) {
sensorCheckedView.setChecked(true);
try {
if(Plot==null) {
Log.e(LOG_TAG, "Plot is null!");
}
mService.mPlotManager.addSignal(deviceMList.get(groupPosition).get(childPosition), Plot);
} catch (Exception e) {
Log.e(LOG_TAG, "Error! + e);
e.printStackTrace();
}
} else {
mService.mPlotManager.removeSignal(deviceMList.get(groupPosition).get(childPosition));
//signalsExpandableListView.setItemChecked(childPosition,false);
sensorCheckedView.setChecked(false);
}
return true;
}
});
Attempt 2 : Creating a different function and call it inside Fragment. Created function is as below and function calling is commented above Attempt 1.
//loop through groups and then children
public void tickCheckboxes() {
//CheckedTextView sensorCheckedView = (CheckedTextView) signalsExpandableListView.findViewById(R.id.sensorsCheckedTextView);
for (int i = 0; i < deviceMList.size(); i++) {
for (int j = 0; j < deviceMList.get(i).size(); j++) {
if (mService.mPlotManager.ifPropertyExist(deviceMList.get(i).get(j))) {
signalsExpandableListView.setItemChecked(j, true);
//sensorCheckedView.setChecked(true);
} else {
signalsExpandableListView.setItemChecked(j, false);
//sensorCheckedView.setChecked(false);
}
}
}
}
Attempt 3 : Accessing child element with ExpandableListView Adapter. I updated the getChildView() method as below.
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
final String childText = (String) getChild(groupPosition,childPosition);
if(view == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.sensors_list_items,null);
}
CheckedTextView txtListChild = (CheckedTextView) view.findViewById((R.id.sensorsCheckedTextView));
txtListChild.setText(childText);
txtListChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtListChild.isChecked()) {
txtListChild.setChecked(false);
} else {
txtListChild.setChecked(true);
}
}
});
return view;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
List Items xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckedTextView
android:id="#+id/sensorsCheckedTextView"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:textColor="#color/black"
android:paddingTop="5dp"
android:paddingBottom="5dp"/>
</LinearLayout>
Group xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/deviceNameTextView"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:text="Device Name"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:background="#color/colorAccent"
android:textColor="#color/colorPrimary"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"/>
</LinearLayout>
What I'm looking for II : For check/uncheck I modified Adapter as in Attempt 4 with the help of the answer mentioned below. I cannot see the checked mark in real-time. When I click a child then I want to scroll up/down to visually see the checkmark. Same as with the uncheck. It is strange. It seems like a kind of "refreshing" is required to see the check/uncheck state in real-time. I would appreciate any suggestions on how to get rid of this.
Thank you.
Attempt 4: Modified adapter. This works for a check/uncheck but can not visually see it in real-time.
public class SignalsExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHandler;
private HashMap<String,List<String>> listHashMap;
private MService mService;
private ArrayList<List<String[]>> deviceMList ;
public SignalsExpandableListAdapter(Context context, List<String> listDataHandler, HashMap<String, List<String>> listHashMap,mService service, ArrayList<List<String[]>> dMList ) {
this.context = context;
this.listDataHandler = listDataHandler;
this.listHashMap = listHashMap;
this.mService = service;
this.deviceMList =dMList;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
final String childText = (String) getChild(groupPosition,childPosition);
if(view == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.sensors_list_items,null);
}
CheckedTextView txtListChild = (CheckedTextView) view.findViewById((R.id.sensorsCheckedTextView));
txtListChild.setText(childText);
if(mService.mPlotManager.ifPropertyExist(deviceMList.get(groupPosition).get(childPosition))) {
txtListChild.setChecked(true);
} else {
txtListChild.setChecked(false);
}
return view;
}
I assume that your mService with a class named PlottingService, then try following changes to the adapter:
public class SignalsExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHandler;
private HashMap<String,List<String>> listHashMap;
private PlottingService mService;
public SignalsExpandableListAdapter(Context context, List<String> listDataHandler, HashMap<String, List<String>> listHashMap, PlottingService ps) {
this.context = context;
this.listDataHandler = listDataHandler;
this.listHashMap = listHashMap;
this.mService = ps;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
final String childText = (String) getChild(groupPosition,childPosition);
if(view == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.sensors_list_items,null);
}
CheckedTextView txtListChild = (CheckedTextView) view.findViewById((R.id.sensorsCheckedTextView));
txtListChild.setText(childText);
// Always set check state according to data.
if(mService.mPlotManager.ifPropertyExist(deviceMList.get(groupPosition).get(childPosition))) {
txtListChild.setChecked(true);
} else {
txtListChild.setChecked(false);
}
return view;
}
Inside Fragment, do Attempt 1, only change:
listAdapter = new SignalsExpandableListAdapter(context,signalsListDataHeader,signalsListHash);
to
listAdapter = new SignalsExpandableListAdapter(context,signalsListDataHeader,signalsListHash, mService);
Hope that helps!
Updated:- In Fragment, comment out the OnChildClickListener and in the adapter, use the following getChildView:
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {
String childText = (String) getChild(groupPosition,childPosition);
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.sensors_list_items,null);
}
CheckedTextView txtListChild = (CheckedTextView) view.findViewById((R.id.sensorsCheckedTextView));
txtListChild.setText(childText);
// Always set check state according to data.
if(mService.mPlotManager.ifPropertyExist(deviceMList.get(groupPosition).get(childPosition))) {
txtListChild.setChecked(true);
} else {
txtListChild.setChecked(false);
}
txtListChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckedTextView sensorCheckedView = (CheckedTextView)v;
if(!sensorCheckedView.isChecked()) {
sensorCheckedView.setChecked(true);
try {
if(Plot==null) {
Log.e(LOG_TAG, "Plot is null!");
}
mService.mPlotManager.addSignal(deviceMList.get(groupPosition).get(childPosition), Plot);
} catch (Exception e) {
Log.e(LOG_TAG, "Error!" + e);
e.printStackTrace();
}
} else {
mService.mPlotManager.removeSignal(deviceMList.get(groupPosition).get(childPosition));
sensorCheckedView.setChecked(false);
}
}
});
return view;
}
Updated 2:- In Fragment, comment out the OnChildClickListener and in the adapter, add a inner class and use the following getChildView:
class Position {
int group, child;
Position(int group, int child) {
this.group = group;
this.child = child;
}
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
String childText = (String) getChild(groupPosition,childPosition);
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.sensors_list_items,null);
}
CheckedTextView txtListChild = (CheckedTextView) view.findViewById((R.id.sensorsCheckedTextView));
txtListChild.setText(childText);
// Always set check state according to data.
if(mService.mPlotManager.ifPropertyExist(deviceMList.get(groupPosition).get(childPosition))) {
txtListChild.setChecked(true);
} else {
txtListChild.setChecked(false);
}
txtListChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckedTextView sensorCheckedView = (CheckedTextView)v;
int groupPosition = ((Position)v.getTag()).group;
int childPosition = ((Position)v.getTag()).child;
if(!sensorCheckedView.isChecked()) {
sensorCheckedView.setChecked(true);
try {
if(Plot==null) {
Log.e(LOG_TAG, "Plot is null!");
}
mService.mPlotManager.addSignal(deviceMList.get(groupPosition).get(childPosition), Plot);
} catch (Exception e) {
Log.e(LOG_TAG, "Error!" + e);
e.printStackTrace();
}
} else {
mService.mPlotManager.removeSignal(deviceMList.get(groupPosition).get(childPosition));
sensorCheckedView.setChecked(false);
}
}
});
txtListChild.setTag(new Position(groupPosition, childPosition));
return view;
}
If Updated 2 still have the issue of multiple checked items, then the possible cause is mService.mPlotManager.ifPropertyExist(deviceMList.get(groupPosition).get(childPosition)). Instead of using mService to verify if an item is selected or not, it may be a better idea to change listHashMap from HashMap<String, List<String>> to HashMap<String, List<ChildItem>> [The accepted answer in Values of counter changes after scrolling ExpendableListView, you need a boolean field instead of the integer field, quantity]. Then when a child item is clicked, check and update with the list.
Could you please tell me why my image not change when I change my expand and collapse the list view .Both time I got same image ..I will show in below image when I expand it display (+) image .why ?
here is my code .
Main activity
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(listDataHeader.get(groupPosition) != null)
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");
// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");
List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");
/*List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");*/
listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
listDataChild.put(listDataHeader.get(1), nowShowing);
listDataChild.put(listDataHeader.get(2), null);
}
}
Adapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
if(this._listDataChild.get(this._listDataHeader.get(groupPosition))!=null)
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
return 0;
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
View ind = convertView.findViewById( R.id.explist_indicator);
if( ind != null ) {
ImageView indicator = (ImageView)ind;
if( getChildrenCount( groupPosition ) == 0 ) {
indicator.setVisibility( View.INVISIBLE );
} else {
indicator.setVisibility( View.VISIBLE );
int stateSetIndex = ( isExpanded ? 1 : 0) ;
Drawable drawable = indicator.getDrawable();
}
}
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
activity.xml
<?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="fill_parent"
android:orientation="vertical"
android:background="#f4f4f4" >
<ExpandableListView
android:id="#+id/lvExp"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:cacheColorHint="#00000000"
android:groupIndicator="#android:color/transparent"
/>
</LinearLayout>
list_group.xml
<?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"
android:padding="8dp"
android:background="#000000">
<ImageView android:src="#drawable/test"
android:id="#+id/explist_indicator"
android:layout_width="20px"
android:layout_height="20px"/>
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="17dp"
android:textColor="#f9f93d" />
</LinearLayout>
list_item.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="55dip"
android:orientation="vertical" >
<TextView
android:id="#+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#000000"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />
</LinearLayout>][1]
I solve that problem by own .Like that
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
View ind = convertView.findViewById(R.id.explist_indicator);
if (ind != null) {
ImageView indicator = (ImageView) ind;
if (isExpanded) {
indicator.setImageResource(R.drawable.icon_3);
} else {
indicator.setImageResource(R.drawable.icon_4);
}
if (getChildrenCount(groupPosition) == 0) {
indicator.setVisibility(View.INVISIBLE);
} else {
indicator.setVisibility(View.VISIBLE);
}
}
return convertView;
}
change Image view like that
<ImageView
android:id="#+id/explist_indicator"
android:layout_width="20px"
android:layout_height="20px"
android:src="#drawable/icon_4" />
Hello i would like to start an activity and also a list view from another activity but i can't understand how to do it.
This is the Expandable adapter
public class MyExpandableAdapter extends BaseExpandableListAdapter
{
#SuppressWarnings("unused")
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
// constructor
public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern)
{
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
// method getChildView is called automatically for each child view.
// Implement this method as per your requirement
#SuppressWarnings("unchecked")
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_view, null);
}
// get the textView reference and set the value
textView = (TextView) convertView.findViewById(R.id.textViewChild);
textView.setText(child.get(childPosition));
// set the ClickListener to handle the click event on child item
/* convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
}); */
return convertView;
}
// method getGroupView is called automatically for each parent item
// Implement this method as per your requirement
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = inflater.inflate(R.layout.parent_view, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return 0;
}
#SuppressWarnings("unchecked")
#Override
public int getChildrenCount(int groupPosition)
{
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.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 boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return false;
}
}
This is my first activity
public class ConversationsListActivity extends ConversationsEssentialActivity{
private String[] drawerListViewItems;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conversations_list);
ActionBar actionBar = getActionBar();
actionBar.show();
FontHelper.applyFont(this, findViewById(R.id.phrasebookList), "fonts/Roboto-Regular.ttf"); /** **/
listView = (ListView) findViewById(R.id.conversationsList);
drawerListViewItems = getResources().getStringArray(R.array.conversations_list_array);
listView.setAdapter(new ArrayAdapter<String>(this,R.layout.conversations_list_items, drawerListViewItems));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
switch (position){
case 0:{
Intent Info = new Intent(ConversationsListActivity.this, ConversationsEssentialActivity.class);
startActivityForResult(Info, position);
setGroupParentsEssential();
setChildDataEssential();
}
break;
}
}
});
}
}
This is my second activity
public class ConversationsEssentialActivity extends Activity{
// Create ArrayList to hold parent Items and Child Items
ArrayList<String> parentItems = new ArrayList<String>();
ArrayList<Object> childItems = new ArrayList<Object>();
ExpandableListView list;
MyExpandableAdapter adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.show();
list = new ExpandableListView(this);
list.setDividerHeight(2);
list.setGroupIndicator(null);
list.setClickable(true);
adapter2 = new MyExpandableAdapter(parentItems, childItems);
adapter2.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
// Set the Adapter to expandableList
list.setAdapter(adapter2);
setContentView(list);
}
// method to add parent Items
public void setGroupParentsEssential()
{
parentItems.add(getResources().getString(R.string.essential_1));
parentItems.add(getResources().getString(R.string.essential_2));
parentItems.add(getResources().getString(R.string.essential_3));
parentItems.add(getResources().getString(R.string.essential_4));
parentItems.add(getResources().getString(R.string.essential_5));
}
// method to set child data of each parent
public void setChildDataEssential()
{
ArrayList<String> child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_1t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_2t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_3t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_4t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_5t));
childItems.add(child);
}
}
the child_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingLeft="0dp"
android:orientation="vertical"
android:id="#+id/childView" >
<TextView
android:id="#+id/textViewChild"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:textSize="20sp"
android:textColor="#75a800"
android:padding="10dp" />
</LinearLayout>
the parent_view.xml
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/textViewGroupName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:textSize="20sp"
android:padding="10dp" />
The first activity, on click, should start the second activity and also launch setGroupParentsEssential(); and setChildDataEssential(); which are declared in the second activity. But on click, it just open the second activity with blank screen.
Does someone provide me an example on how to solve this?
Thank you
If you have created a layout for your activity, try referencing this layout using:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmlfile);
...
}
The layout itself should define the listview
HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link