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
Related
I have a custom 'ArrayAdapter' in a 'ListView', my problem is using a menu 'SearchView'. It's not working properly. I don´t know if the problem is searching or showing the results, because nothing appears. And, if possible, I wnat to show a custom list of results. Thanks!
Fragment with the adapter
ArrayList<Favoritos> favorites;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.list_item, container, false);
favorites = new ArrayList<Favoritos>();
favorites.add(new Favorites("Title", "addres", 5, false, 7, 22, 4.5f));
favorites.add(new Favorites("Title", "addres", 3.5 , true, 7, 22, 3.0f));
favorites.add(new Favorites("Title", "addres", 2, false, 7, 22, 4.0f));
favorites.add(new Favorites("Titleo", "addres", 4.5, true, 7, 22, 5.0f));
FavoritesAdapter adapter = new FavoritesAdapter(getActivity(), favorites);
ListView listView = (ListView) rootView.findViewById(R.id.list_item);
listView.setAdapter(adapter);
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String string) {
search(string);
return true;
}
//This is the search method
public void search(String s) {
if (s == null || s.trim().equals("")) {
cleanSearch(); //In this method I just "reset" the adapter when the user "give up"
return;
}
ArrayList<Favoritos> estacionamentosEncontrados = new ArrayList<Favoritos>(favoritos);
for (int i = estacionamentosEncontrados.size() - 1; i >= 0; i--) {
Favoritos estacionamento = estacionamentosEncontrados.get(i);
Favoritos nenhumResultado = new Favoritos("Nenhum resultado encontrado");
if (!estacionamento.mIndicacao.toUpperCase().contains(s.toUpperCase())) {
estacionamentosEncontrados.remove(estacionamento);
} else {
estacionamentosEncontrados.add(nenhumResultado);
}
}
adapter = new EncontradosAdapter(getActivity(), estacionamentosEncontrados);
ListView listView = (ListView) getActivity().findViewById(R.id.list_item);
listView.setAdapter(adapter);
}
Favorites.java
public String mIndicacao;
public String mEndereco;
private double mPreco;
public boolean mDisponibilidade;
private double mHoraAbre;
private double mHoraFecha;
private float mAvaliacao;
public Favoritos(){
}
public Favoritos(String indicacao, String endereco, double preco, boolean disponibilidade, double horaAbre, double horaFecha, float avaliacao){
mIndicacao = indicacao;
mEndereco = endereco;
mPreco = preco;
mDisponibilidade = disponibilidade;
mHoraAbre = horaAbre;
mHoraFecha = horaFecha;
mAvaliacao = avaliacao;
}
//Getters and Setters
And the custom Adapter
public class FavoritesAdapter extends ArrayAdapter<Favorites> {
public FavoritesAdapter(Context context, ArrayList<Favorites> favorites){
super(context, 0, favoritos);
}
public static class ItemViewHolder{
TextView indicadorTextView;
TextView enderecoTextView;
TextView precoTextView;
TextView horaAbreTextView;
TextView horaFechaTextView;
RatingBar notaEstacionamento;
ImageView disponivelImg;
TextView disponivelTextView;
ImageView esconderView;
public ItemViewHolder(View view){
indicadorTextView = (TextView) view.findViewById(R.id.indicador);
enderecoTextView = (TextView) view.findViewById(R.id.endereco);
precoTextView = (TextView) view.findViewById(R.id.precoValor);
horaAbreTextView = (TextView) view.findViewById(horaAbre);
horaFechaTextView = (TextView) view.findViewById(horaFecha);
notaEstacionamento = (RatingBar) view.findViewById(R.id.ratingBar);
disponivelImg = (ImageView) view.findViewById(R.id.img_disponibilidade);
disponivelTextView = (TextView) view.findViewById(R.id.disponivel);
esconderView = (ImageView) view.findViewById(R.id.esconder_view_btn);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.favorites_item, parent, false);
}
Favorites currentFavorito = getItem(position);
final ItemViewHolder holder;
if(listItemView.getTag() == null){
holder = new ItemViewHolder(listItemView);
listItemView.setTag(holder);
} else {
holder = (ItemViewHolder) listItemView.getTag();
}
if(currentFavorito.getDisponibilidade()){
holder.disponivelTextView.setText(currentFavorito.getIndicacao());
} else {
holder.disponivelTextView.setText(currentFavorito.getIndicacao());
}
holder.indicadorTextView.setText(currentFavorito.getIndicacao());
holder.enderecoTextView.setText(currentFavorito.getEndereco());
holder.precoTextView.setText(currentFavorito.getPreco());
holder.horaAbreTextView.setText(currentFavorito.getHoraAbre());
holder.horaFechaTextView.setText(currentFavorito.getHoraFecha());
holder.notaEstacionamento.setRating(currentFavorito.getAvaliacao());
if(currentFavorito.getDisponibilidade()){
holder.disponivelImg.setImageResource(R.drawable.ir_img);
holder.disponivelTextView.setText(R.string.aberto);
holder.disponivelTextView.setTextColor(getContext().getResources().getColor(R.color.verde));
} else {
holder.disponivelImg.setImageResource(R.drawable.fechado_img);
holder.disponivelTextView.setText(R.string.fechado);
holder.disponivelTextView.setTextColor(getContext().getResources().getColor(R.color.vermelho)); }
return listItemView;
}
}
Step : 1 Create option menu in fragment for searchview like
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
//menu.clear();
inflater.inflate(R.menu.ticket_fragment_search_menu, menu);
MenuItem actionSearch = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(actionSearch);
searchView.setMaxWidth(Integer.MAX_VALUE);
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setSingleLine(true);
searchEditText.setTextColor(getResources().getColor(R.color.black));
searchEditText.setHintTextColor(getResources().getColor(R.color.black));
searchView.setQueryHint(getResources().getString(R.string.txt_search_here));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//apply Filter
adapter.setFilter(newText)
return false;
}
});
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "search open");
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
Log.e(TAG, "search close");
return false;
}
});
}
Step 2 : create function for filter or search in adapter
public void setFilter(String str) {
aList = new ArrayList<>();
if (aListTemp.size() > 0) {
for (int i = 0; i < aListTemp.size(); i++) {
if (aListTemp.get(i).toLowerCase().contains(str.toLowerCase())
) {
aList.add(aListTemp.get(i));
}
}
}
notifyDataSetChanged();
}
In each row, I have a button and a textView. When the Button is clicked, It successfully sets the textView to a new value in that row. However, When I call ParseQuery() in GetView(); and try to do object.put("objectName", num) The only value that is populated to my Parse-Server is the last row. My SetTag(); and GetTag(); and ViewHolder class is correct When I click the button, I believe android studio is unsure of which row's TextView to populate so it just automatically populates the last row's TextView.
Custom ListView Adapter Class
public class CustomFeedListViewAdapter extends BaseAdapter {
String likesString;
int position;
private Context mContext;
private ArrayList<HashMap<String, String>> feed;
private static LayoutInflater inflater = null;
ParseObject parseObFeed;
public CustomFeedListViewAdapter(Context context, ArrayList<HashMap<String, String>> data) {
super();
this.mContext = context;
this.feed = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return feed.size();
}
#Override
public Object getItem(int i) {
return feed.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
position = i;
final ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.feed_list_row, viewGroup, false);
holder = new ViewHolder();
holder.feedProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
holder.feedUsername = (TextView) view.findViewById(R.id.feedUsernameId);
holder.feedNumOfLikes = (TextView) view.findViewById(R.id.feedNumofLikes);
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
view.setTag(holder);
HashMap<String, String> mFeed = new HashMap<>();
mFeed = feed.get(i);
holder.feedNumOfLikes.setText(mFeed.get("likes"));
likesString = mFeed.get("likes");
holder.mLikes = Integer.valueOf(likesString);
position = i;
}
else{
position = i;
holder = (ViewHolder) view.getTag();
}
holder.feedUpVoteButton.setTag(position);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("FeedItem");
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
for (final ParseObject object : objects) {
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject[] mParseObject = new ParseObject[feed.size()];
int pos = (Integer) v.getTag();
mParseObject[pos] = object;
holder.likes[pos] = holder.mLikes;
mParseObject[pos].put("likes", holder.likes[pos]);
mParseObject[pos].saveInBackground();
holder.feedNumOfLikes.setText(String.valueOf(holder.likes[pos]
));
}
});
}
}
}
});
return view;
}
class ViewHolder {
ImageView feedProfilePic;
TextView feedUsername;
TextView feedNumOfLikes;
TextView feedFeedItem;
TextView feedDate;
TextView feedNumofReplies;
Button feedUpVoteButton;
Button feedDownVoteButton;
Button feedCommentButton;
ListView feedListView;
int likes[] = new int[feed.size()];
int mLikes;
}
}
In my Expandable Listview, have three groups. I want to add different three image for that group. i tried many codes, but not working.
My code:
Main Activity:
HashMap<String, List<String>> rightDrawerListDetail = getData();
List<String> rightDrawerListTitle = new ArrayList<String>(rightDrawerListDetail.keySet());
adapterR = new CustomExpandableListAdapter(this, rightDrawerListTitle,rightDrawerListDetail);
mRightDrawerList.setAdapter(adapterR);
private HashMap<String, List<String>> getData(){
HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();
ArrayList<String> arrayList = mydb.getAllAddress();
List asRider = new ArrayList();
asRider.add("hello");
List asRidee = new ArrayList();
asRidee.add("hai");
List recent = new ArrayList();
recent.add("Success");
expandableListDetail.put("As a Rider",asRider);
expandableListDetail.put("As a Ridee",asRidee);
expandableListDetail.put("My Recent Activities",recent);
return expandableListDetail;
}
CustomExpandableListAdapter.java:
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private List<String> mGroups;
private LayoutInflater mInflater;
private HashMap<String, List<String>> mexpandableListDetail;
public CustomExpandableListAdapter(Context context, List<String> groups,HashMap<String, List<String>> expandableListDetail) {
mContext = context;
mGroups = groups;
mexpandableListDetail = expandableListDetail;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getGroupCount() {
return mGroups.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return mexpandableListDetail.get(mGroups.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return mGroups.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return mexpandableListDetail.get(mGroups.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.right_drawer_group, null);
}
// Get the group item
String listTitle = (String) getGroup(groupPosition);
// Set group name
TextView textView = (TextView) convertView.findViewById(R.id.textGroup);
textView.setText(listTitle);
ImageView indicator = (ImageView) convertView.findViewById(R.id.groupIndicator);
if (isExpanded) {
indicator.setImageResource(R.drawable.arrowup);
} else {
indicator.setImageResource(R.drawable.arrowdown);
}
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.right_drawer_child, null);
}
// Get child name
String children = (String) getChild(groupPosition, childPosition);
// Set child name
TextView text = (TextView) convertView.findViewById(R.id.textChild);
text.setText(children);
/*convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, children, Toast.LENGTH_SHORT).show();
}
});*/
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Please anyone help to me!
Thanks in advance
In your right_drawer_group.xml add an ImageView where you want your group image to be placed, lets say groupImage.
In your getGroupView:
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.right_drawer_group, null);
}
//Set group image
ImageView groupImage = (ImageView)convertView.findViewById(R.id.groupImage);
switch((String)getGroup(groupPosition))
{
case "As a Rider":
//groupImage set correct image
break;
case "As a Ridee":
//groupImage set correct image
break;
case "My Recent Activities":
//groupImage set correct image
break;
}
// Get the group item
String listTitle = (String) getGroup(groupPosition);
// Set group name
TextView textView = (TextView) convertView.findViewById(R.id.textGroup);
textView.setText(listTitle);
ImageView indicator = (ImageView) convertView.findViewById(R.id.groupIndicator);
if (isExpanded) {
indicator.setImageResource(R.drawable.arrowup);
} else {
indicator.setImageResource(R.drawable.arrowdown);
}
return convertView;
}
It's not the most neat solution as if you change the group name this will break, but it will work for now. Better solution would be is to pass the groups as objects containing getName and getImageId.
In my app I need to show images inside a expandableListView and it has to be a gridview of images, and these images can be selectable so I have an expandableListAdapter and inside of it I'm implementing a gridview adapter,
the images are showing fine as you can see in the picture 1, now what I'm trying to achieve is the picture 2, how can I pass the groupPosition and the childPosition to the gridAdapter and whe I click on the image make it highlight? :
Picture 2:
public class ExpandListAdapter extends BaseExpandableListAdapter {
public static final int CHOICE_MODE_MULTIPLE = AbsListView.CHOICE_MODE_MULTIPLE;
public static final int CHOICE_MODE_MULTIPLE_MODAL = AbsListView.CHOICE_MODE_MULTIPLE_MODAL;
/**
* No child could be selected
*/
public static final int CHOICE_MODE_NONE = AbsListView.CHOICE_MODE_NONE;
/**
* One single choice per group
*/
public static final int CHOICE_MODE_SINGLE_PER_GROUP = AbsListView.CHOICE_MODE_SINGLE;
/**
* One single choice for all the groups
*/
public static final int CHOICE_MODE_SINGLE_ABSOLUTE = 10001;
private Context context;
private ArrayList<Group> groups;
private ArrayList<ArrayList<Child>> child = new ArrayList();
private ArrayList<Child> listchild;
private GridAdapter adapter;
private CustomGridView gridView;
private SparseArray<SparseBooleanArray> checkedPositions;
private static final String LOG_TAG = ExpandListAdapter.class.getSimpleName();
private int choiceMode = CHOICE_MODE_MULTIPLE;
public ExpandListAdapter(Context context, ArrayList<Group> groups) {
this.context = context;
this.groups = groups;
checkedPositions = new SparseArray<SparseBooleanArray>();
child = new ArrayList();
for (int i = 0; i < groups.size(); i++) {
child.add(i, groups.get(i).getItems());
}
}
public ExpandListAdapter(Context context, ArrayList<Group> children, int choiceMode) {
this(context, children);
// For now the choice mode CHOICE_MODE_MULTIPLE_MODAL
// is not implemented
if (choiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
throw new RuntimeException("The choice mode CHOICE_MODE_MULTIPLE_MODAL " +
"has not implemented yet");
}
this.choiceMode = choiceMode;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return child.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.gridview, null);
}
listchild = new ArrayList<Child>();
for (int j = 0; j < groups.get(groupPosition).getItems().size(); j++) {
listchild.add(child.get(groupPosition).get(j));
}
gridView = (CustomGridView) convertView.findViewById(R.id.GridView_toolbar);
gridView.setExpanded(true);
adapter = new GridAdapter(context, listchild, checkedPositions, groupPosition, childPosition);
gridView.setAdapter(adapter);// Adapter
gridView.setChoiceMode(CustomGridView.CHOICE_MODE_MULTIPLE);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setClicked(groupPosition, childPosition);
System.out.println("position" + checkedPositions.get(groupPosition));
if (checkedPositions.get(groupPosition) != null) {
boolean isChecked = checkedPositions.get(groupPosition).get(childPosition);
if(!isChecked){
}
} else {
System.out.println("false");
}
}
});
return convertView;
}
public void setClicked(int groupPosition, int childPosition) {
switch (choiceMode) {
case CHOICE_MODE_MULTIPLE:
SparseBooleanArray checkedChildPositionsMultiple = checkedPositions.get(groupPosition);
// if in the group there was not any child checked
if (checkedChildPositionsMultiple == null) {
checkedChildPositionsMultiple = new SparseBooleanArray();
// By default, the status of a child is not checked
// So a click will enable it
checkedChildPositionsMultiple.put(childPosition, true);
checkedPositions.put(groupPosition, checkedChildPositionsMultiple);
} else {
boolean oldState = checkedChildPositionsMultiple.get(childPosition);
checkedChildPositionsMultiple.put(childPosition, !oldState);
}
break;
// TODO: Implement it
case CHOICE_MODE_MULTIPLE_MODAL:
throw new RuntimeException("The choice mode CHOICE_MODE_MULTIPLE_MODAL " +
"has not implemented yet");
case CHOICE_MODE_NONE:
checkedPositions.clear();
break;
case CHOICE_MODE_SINGLE_PER_GROUP:
SparseBooleanArray checkedChildPositionsSingle = checkedPositions.get(groupPosition);
// If in the group there was not any child checked
if (checkedChildPositionsSingle == null) {
checkedChildPositionsSingle = new SparseBooleanArray();
// By default, the status of a child is not checked
checkedChildPositionsSingle.put(childPosition, true);
checkedPositions.put(groupPosition, checkedChildPositionsSingle);
} else {
boolean oldState = checkedChildPositionsSingle.get(childPosition);
// If the old state was false, set it as the unique one which is true
if (!oldState) {
checkedChildPositionsSingle.clear();
checkedChildPositionsSingle.put(childPosition, !oldState);
} // Else does not allow the user to uncheck it
}
break;
// This mode will remove all the checked positions from other groups
// and enable just one from the selected group
case CHOICE_MODE_SINGLE_ABSOLUTE:
checkedPositions.clear();
SparseBooleanArray checkedChildPositionsSingleAbsolute = new SparseBooleanArray();
checkedChildPositionsSingleAbsolute.put(childPosition, true);
checkedPositions.put(groupPosition, checkedChildPositionsSingleAbsolute);
break;
}
// Notify that some data has been changed
notifyDataSetChanged();
Log.v(LOG_TAG, "List position updated");
Log.v(LOG_TAG, PrintSparseArrays.sparseArrayToString(checkedPositions));
}
public void setChoiceMode(int choiceMode) {
this.choiceMode = choiceMode;
// For now the choice mode CHOICE_MODEL_MULTIPLE_MODAL
// is not implemented
if (choiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
throw new RuntimeException("The choice mode CHOICE_MODE_MULTIPLE_MODAL " +
"has not implemented yet");
}
checkedPositions.clear();
Log.v(LOG_TAG, "The choice mode has been changed. Now it is " + this.choiceMode);
}
#Override
public int getChildrenCount(int nGroup) {
return 1;
}
#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) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.group_item, null);
}
ExpandableListView mExpandableListView = (ExpandableListView) parent;
mExpandableListView.expandGroup(groupPosition);
TextView tv = (TextView) convertView.findViewById(R.id.group_name);
tv.setText(group.getName());
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
GridAdapter:
public class GridAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Child> child;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private SparseArray<SparseBooleanArray> checkedPositions;
int groupPosition, childPosition;
public GridAdapter(Context context, ArrayList<Child> childValues, SparseArray<SparseBooleanArray> checkedPositions, int groupPosition, int childPosition) {
mContext = context;
child = childValues;
this.checkedPositions = checkedPositions;
this.childPosition = childPosition;
this.groupPosition = groupPosition;
}
#Override
public int getCount() {
return child.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NetworkImageView i;
childPosition = position;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_item, null);
holder = new ViewHolder();
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
i = (NetworkImageView) convertView
.findViewById(R.id.flag);
i.setImageUrl(String.valueOf(child.get(childPosition).getImage()), imageLoader);
convertView.setTag(holder);
System.out.println("position" + checkedPositions.get(groupPosition));
if (checkedPositions.get(groupPosition) != null) {
boolean isChecked = checkedPositions.get(groupPosition).get(childPosition);
i.setBackgroundResource(R.color.bg);
if(!isChecked){
}
} else {
System.out.println("false");
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text = (TextView) convertView.findViewById(R.id.label);
holder.text.setText(child.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView text;
}
}
In My Assumption
ExpandListAdapter Class
In getChildView() method childPosition does not depends on what country flag is being clicked , Because childPosition here returns the position of the Grid view, not the flags under it
So, no need to pass childPosition in constructor of GridView ,since childPosition will always return 1
To get actual flag clicked position Use onClickListener inside your GridAdapter like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NetworkImageView i;
childPosition = position;
if (convertView == null) {
} else {
holder = (ViewHolder) convertView.getTag();
}
convertView.setOnclickListener(new OnClickListener{
#Override
onClick(View v){
isChecked=child.get(childPosition).isChecked();
if(!isChecked){
child.get(childPosition).setChecked(true);
}
else {
child.get(childPosition).setChecked(false);
}
});
No need to handle checked positions separately create two methods in your child class isChecked() and setChecked() to maintain check-uncheck state of flags.
Change color of selected or checked flag here
holder.text = (TextView) convertView.findViewById(R.id.label);
holder.text.setText(child.get(position).getName());
return convertView;
}
and remove your Check logic from ExpandListAdapter Class :
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setClicked(groupPosition, childPosition);
System.out.println("position" + checkedPositions.get(groupPosition));
if (checkedPositions.get(groupPosition) != null) {
boolean isChecked = checkedPositions.get(groupPosition).get(childPosition);
if(!isChecked){
}
} else {
System.out.println("false");
}
}
});
You need to set an 'OnItemClickListener' to your gridAdapter, and overide the onItemClick method as following.
Note :- This will highlight the ImageView you click and if you happened to click another ImageView in the same GridView, that ImageView also will be highlighted! Like in a 'multiple selection'.
gridAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView selectedFlagImageView = (ImageView) view;
selectedFlagImageView.setBackgroundColor(Color.parseColor("#37a93400"));
}
});
This will color the background of the selected ImageView. Color code I've used in here is simply, more alpha and less RGBs.(I used Android Studio color chooser)
Following images will give you an idea about how it will look when giving a background color like this.
Without background color :
With background color :
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