Trying to set custom BaseAdapter to listview - java

I am trying to accomplish this: http://blog.uncommons.org/2011/05/09/embedding-admob-adverts-in-android-listviews/.
I am stuck at setting the custom BaseAdapter I simply don't know what to put in the BASEADAPTER variable below.
Here is my adapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
/**
* List adapter decorator that inserts adverts into the list.
* #author Daniel Dyer
*/
public class AdvertisingAdapter extends BaseAdapter
{
private static final String ADMOB_PUBLISHER_ID = "---------------";
private final Activity activity;
private final BaseAdapter delegate;
private int resource;
private ArrayList<String> objects;
public AdvertisingAdapter(Activity activity, int resource, BaseAdapter delegate,
ArrayList<String> stories) {
// TODO Auto-generated constructor stub
this.resource = resource;
this.activity = activity;
this.delegate = delegate;
this.objects = stories;
delegate.registerDataSetObserver(new DataSetObserver()
{
#Override
public void onChanged()
{
notifyDataSetChanged();
}
#Override
public void onInvalidated()
{
notifyDataSetInvalidated();
}
});
}
public int getCount()
{
return delegate.getCount() + 1;
}
public Object getItem(int i)
{
return delegate.getItem(i - 1);
}
public long getItemId(int i)
{
return delegate.getItemId(i - 1);
}
public View getView(int position, View convertView, ViewGroup parent)
{
if ((position % 10) == 0)
{
if (convertView instanceof AdView)
{
return convertView;
}
else
{
AdView adView = new AdView(activity, AdSize.BANNER, ADMOB_PUBLISHER_ID);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Default layout params have to be converted to ListView compatible
// params otherwise there will be a ClassCastException.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params
= new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
adView.loadAd(new AdRequest());
return adView;
}
}
else
{
return delegate.getView(position - 1, convertView, parent);
}
}
#Override
public int getViewTypeCount()
{
return delegate.getViewTypeCount() + 1;
}
#Override
public int getItemViewType(int position)
{
return position == 0 ? delegate.getViewTypeCount()
: delegate.getItemViewType(position - 1);
}
#Override
public boolean areAllItemsEnabled()
{
return false;
}
#Override
public boolean isEnabled(int position)
{
return position != 0 && delegate.isEnabled(position - 1);
}
}
And in my main activity here is where I'm trying to set my custom base adapter. What should the BASEADAPTER parameter be?
mListView.setAdapter(new AdvertisingAdapter(this,
android.R.layout.simple_list_item_1, BASEADAPTER, stories));

Its depend what you trying to show or display in listview, normally application context and desire data is to be passed to BaseAdapter constructor. For details info read BaseAdapter and even check Android ListView detailed tutorial.

Related

How can I add OnClickListener to PagerAdapter

I'm using PagerAdaper for image slide in my app. I want to add listener on it mean if the image show when i click on it it say something. let suppose i have an image of apple now i want to add listener on it when i click on it it say apple. i want to add the same on all raw files.
package com.example.slider;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
private Context mcontext;
private int[] myImages = new int[] {R.raw.one , R.raw.two, R.raw.three,
R.raw.four , R.raw.five , R.raw.six, R.raw.seven, R.raw.eight,
R.raw.nine, R.raw.ten, R.raw.eleven, R.raw.twele , R.raw.thirteen, R.raw.fourteen,
R.raw.fifteen, R.raw.one_image, R.raw.two_image,
R.raw.three_image, R.raw.four_image, R.raw.five_image,
R.raw.six_image, R.raw.seven_image};
ImageAdapter(Context context){
mcontext = context;
}
#Override
public int getCount() {
return myImages.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(mcontext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(myImages[position]);
container.addView(imageView,0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position,Object object) {
container.removeView((ImageView)object);
}
}
There are several different possible solutions. One way to connect each view with its image resource using a HashMap.
public class ImageAdapter extends PagerAdapter {
private Context mcontext;
private int[] myImages = new int[] {R.raw.one , R.raw.two, R.raw.three,
R.raw.four , R.raw.five , R.raw.six, R.raw.seven, R.raw.eight,
R.raw.nine, R.raw.ten, R.raw.eleven, R.raw.twele , R.raw.thirteen, R.raw.fourteen,
R.raw.fifteen, R.raw.one_image, R.raw.two_image,
R.raw.three_image, R.raw.four_image, R.raw.five_image,
R.raw.six_image, R.raw.seven_image};
ImageAdapter(Context context){
mcontext = context;
}
private HashMap<View, Integer> viewToImageResource = new HashMap<>();
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer clickedImageResource = viewToImageResource.get(v);
// Do something with clickedImageResource
}
};
#Override
public int getCount() {
return myImages.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(mcontext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(myImages[position]);
container.addView(imageView,0);
viewToImageResource.put(container, myImages[position]);
container.setOnClickListener(clickListener);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position,Object object) {
container.removeView((ImageView)object);
}
}

ListView with customAdapter not updated when notifyDataSetChanged is called?

I have a Listview with two adapters. They receive an Array with some data and when scrolled to bottom of the listview more data is loaded into the Array and here the listview should add the new data.
Question:
How can I make the listview reflect the new data and why isn't it updated when I call adAdapter.notifyDataSetChanged(); ?
Fragments inner class where I download data & update UI in onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
// list.setAdapter(adapter); this works when adapter.notifyDataSetChanged(); also is in the else statement but here I don't use the BannerAdListView2 adapter which i want to?
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
// adapter.notifyDataSetChanged(); // Here the listview should get refresh with the new data
adAdapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
// Attach the listener to the AdapterView onCreate
list.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if(pageNumberInt < totalPagesInt){
++incre;
new DownloadJSON().execute();
}
}
});
}
Here is my SearchListViewAdapter:
public class SearchListViewAdapter extends BaseAdapter{
Context context;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> mylist = new HashMap<>();
static String url;
static String title;
public SearchListViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.list_image);
holder.textForTitle = (TextView) convertView.findViewById(R.id.search_title);
holder.textForTitle.setTag(position);
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
holder.textForTitle.setTag(data.get(position));
}
mylist = data.get(position);
final String mediaType = mylist.get("media_type");
if (mediaType.equals("movie")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("title");
} else if (mediaType.equals("tv")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("original_name");
} else {
String posterPath = mylist.get("profile_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("name");
}
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
// load image url into poster
Picasso.with(context).load(url).into(holder.poster);
// set title to textview
holder.textForTitle.setText(title);
return convertView;
}
class ViewHolder {
ImageView poster;
TextView textForTitle;
}
}
And my BannerAdListView2 adapter:
public class BannerAdListView2 extends BaseAdapter
{
Activity activity;
Context context;
BaseAdapter delegate;
int k = 7;
int baseItems;
int noAds;
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Total count includes list items and ads.
return baseItems + noAds;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(getOffsetPosition(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + noAds;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
if (position < k) return false;
// Calculate current offset caused by ads already embedded
if (position==k){
return true;
}
else {
return isItemAnAd(position-k);
}
}
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
int currentNoAds = position / k;
return position - currentNoAds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Display every n list items
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
// Don’t instantiate new AdView, reuse old one
return convertView;
} else {
// Create a new AdView
AdView adView = new AdView(activity);
adView.setAdSize(AdSize.BANNER);
String bannerId = "My unit id";
adView.setAdUnitId(bannerId);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Convert the default layout parameters so that they play nice with
// ListView.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest bannerIntermediateReq = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("d9e108ab") //means that a test ad is shown on my phone
.build();
adView.loadAd(bannerIntermediateReq);
return adView;
}
} else {
// Offload displaying other items to the delegate
return delegate.getView(getOffsetPosition(position) ,
convertView, parent);
}
}
}
Edit:
Changed the constructor of BannerAdListView2
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, final BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
delegate.registerDataSetObserver(new DataSetObserver() {
public void onChanged() {
baseItems = delegate.getCount();
noAds = baseItems / k;
}
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
And in fragment
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
adapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
}
Try this solution ... DecorerAdapter:
public static abstract class DecorerAdapter extends BaseAdapter {
public int DECORER_ITEM_TYPE;
private final BaseAdapter mInnerAdapter;
private final int mRepeatAfterEvery;
private int mCount;
public DecorerAdapter(BaseAdapter innerAdapter, int repeatAfterEvery) {
mInnerAdapter = innerAdapter;
mRepeatAfterEvery = repeatAfterEvery;
mInnerAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
setupAdapter();
}
#Override
public void notifyDataSetChanged() {
setupAdapter();
super.notifyDataSetChanged();
}
private void setupAdapter(){
mCount = mInnerAdapter.getCount();
mCount += (mCount + mRepeatAfterEvery - 2) / (mRepeatAfterEvery - 1);
DECORER_ITEM_TYPE = mInnerAdapter.getViewTypeCount();
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(int position) {
if(position % mRepeatAfterEvery == 0)
return null;
return mInnerAdapter.getItem(calculateInnerPosition(position));
}
private int calculateInnerPosition(int position) {
return position - (position + mRepeatAfterEvery - 1) / mRepeatAfterEvery;
}
#Override
public long getItemId(int position) {
if(position % mRepeatAfterEvery == 0)
return -1;
return mInnerAdapter.getItemId(calculateInnerPosition(position));
}
#Override
public int getItemViewType(int position) {
if(position % mRepeatAfterEvery == 0)
return DECORER_ITEM_TYPE;
return mInnerAdapter.getItemViewType(calculateInnerPosition(position));
}
#Override
public boolean hasStableIds() {
return mInnerAdapter.hasStableIds();
}
#Override
public int getViewTypeCount() {
return mInnerAdapter.getViewTypeCount() + 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position % mRepeatAfterEvery == 0)
return getDecorerView((position + mRepeatAfterEvery - 1) / mRepeatAfterEvery, convertView, parent);
return mInnerAdapter.getView(calculateInnerPosition( position), convertView, parent);
}
public abstract View getDecorerView(int position, View convertView, ViewGroup parent);
}
code with usage:
package pl.selvin.decoreradapter;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
/*** paste the DecorerAdapter class here ***/
public static class MyListFragment extends ListFragment{
final ArrayList<String> strings = new ArrayList<>();
private BaseAdapter innerAdapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add("Add rnd(10) more");
super.onCreateOptionsMenu(menu, inflater);
}
final Random rnd = new Random();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final String[] toAdd = new String[rnd.nextInt(10)];
int start = strings.size();
for(int i = 0; i < toAdd.length; i++)
toAdd[i] = (start + i) + "";
Collections.addAll(strings, toAdd);
Toast.makeText(getActivity(), "Added " + toAdd.length + " count: " + strings.size(), Toast.LENGTH_SHORT).show();
innerAdapter.notifyDataSetChanged();
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
for(int i = 0; i < 4; i++) {
strings.add(i + "");
}
innerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, strings);
setListAdapter(new DecorerAdapter(innerAdapter, 5) {
#Override
public View getDecorerView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = new TextView(getActivity());
convertView.setBackgroundColor(Color.RED);
}
((TextView)convertView).setText("AdView: " + position);
return convertView;
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String)l.getItemAtPosition(position);
Toast.makeText(getActivity(), "Item click: " + (item == null ? "ADVIEW" : item), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new MyListFragment(), "LIST").commit();
}
}
}
It repeats decorer view at every element passed to the constructor ...
all you need to do is implement getDecorerView in the similar way as getView in normal adapter

How to put icon in SlidingTab?

How i can put icon in my tab using SlidingTabLayout. I just want to change the Titles into Icon. Please help me on how to do it.
Here is the code
ViewPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
OrderTab ordertab = new OrderTab();
return ordertab;
}
else if(position==1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
ViewOrderTab viewordertab = new ViewOrderTab();
return viewordertab;
}
else
{
OrderStatus orderstatus = new OrderStatus();
return orderstatus;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
public static interface FirstShot
{
public void onFirstShot();
}
}
SlidingTabLayout.java
package com.example.work.mcoatorderingapp;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* To be used with ViewPager to provide a tab indicator component which give constant feedback as to
* the user's scroll progress.
* <p>
* To use the component, simply add it to your view hierarchy. Then in your
* {#link android.app.Activity} or {#link android.support.v4.app.Fragment} call
* {#link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for.
* <p>
* The colors can be customized in two ways. The first and simplest is to provide an array of colors
* via {#link #setSelectedIndicatorColors(int...)}. The
* alternative is via the {#link TabColorizer} interface which provides you complete control over
* which color is used for any individual position.
* <p>
* The views used as tabs can be customized by calling {#link #setCustomTabView(int, int)},
* providing the layout ID of your custom layout.
*/
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {#link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* #return return the color of the indicator used when {#code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void OnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
tabTitleView.setTextSize(14);
}
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
The Fragments are OrderTab.java the same code with ViewOrderTab.java and OrderStatus.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OrderStatus extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.orderstatus_list,container,false);
return v;
}
}
MainActivity.java
EditText search;
ProgressDialog pDialog;
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Order Product", "Cart", "Order Status"};
int Numboftabs = 3;
String titlebar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs=(SlidingTabLayout)
findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer()
{
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
}
);
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
Try
private int[] imageResId = {
R.drawable.ic_home,
R.drawable.ic_my_timeline,
R.drawable.ic_my_pages,
R.drawable.ic_my_groups,
R.drawable.ic_liked_pages
};
#Override
public CharSequence getPageTitle(int position) {
Drawable image = mContext.getResources().getDrawable(imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
instead of
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
in your ViewPagerAdapter class.
EDIT1:
In your activity change
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
to
adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), Titles, Numboftabs);
Then in your ViewPagerAdapter following changes are needed.
Context mContext;
public ViewPagerAdapter(Context context, FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.mContext = context;
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
EDIT2:
try extending FragmentPagerAdapter instead of FragmentStatePagerAdapter in your ViewPagerAdapter.
In your main activity code should be this:
tabs=(SlidingTabLayout)findViewById(R.id.tabs);
tabs.setCustomTabView(R.layout.custom_tab, 0);
Here is custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold"
android:background="?android:selectableItemBackground"
android:padding="16dp"
android:gravity="center" />
hope this helps!

Android infinitely scrolling list in both directions

I'm trying to figure out how to implement an infinitely scrolling list. It will display a calendar and events and it should start from now or selected date. It should be scrollable in both directions, past and future. The solutions with OnScrollListener here seem to work pretty well if I only need to go to future (index just grows bigger). But I don't see how I would go to the past.
This solution seems to be very wasteful for my case. getView is called thousands of times. Maybe ListView isn't the solution, and I'll have to go with lower-level code. Any ideas?
EDIT: getView being called thousands of times wasn't the fault of the latter solution. However, it still gets called too many times and with wrong values. If I set selection like this:
myList.setSelection(Integer.MAX_VALUE/2)
I get getView calls with indexes starting from zero. For example, I get getView calls like this:
getView pos 0
...
getView pos 26
and then
getView pos 1073741823
...
getView pos 1073741847
Which are the correct ones. Then:
getView pos 0
...
getView pos 26
again
This all happens before I scroll or touch the screen at all. Doesn't seem to make much sense.
Here is an implementation of this task.
EndlessScrollBaseAdapter.java
package com.example.endlessscrollinbothdirections;
import java.util.Map;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
/** A child class shall subclass this Adapter and implement method getDataRow(int position,
* View convertView, ViewGroup parent), which supplies a View present data in a ListRow.
* This parent Adapter takes care of displaying ProgressBar in a row or indicating that it
* has reached the last row. */
public abstract class EndlessScrollBaseAdapter<T> extends BaseAdapter implements
OnScrollListener {
private int mVisibleThreshold = 5;
// the main data structure to save loaded data
protected Map<Integer, T> mItems;
protected Context mContext;
// the serverListSize is the total number of items on the server side,
// which should be returned from the web request results
protected int mServerListSize = -1;
// Two view types which will be used to determine whether a row should be displaying
// data or a Progressbar
public static final int VIEW_TYPE_LOADING = 0;
public static final int VIEW_TYPE_ACTIVITY = 1;
public static final int VIRTUAL_MIDDLE_OFFSET = Integer.MAX_VALUE / 2;
public EndlessScrollBaseAdapter(Context context, Map<Integer, T> items) {
mContext = context;
mItems = items;
}
public void setServerListSize(int serverListSize) {
this.mServerListSize = serverListSize;
}
/** disable click events on indicating rows */
#Override
public boolean isEnabled(int position) {
return getItemViewType(position) == EndlessScrollBaseAdapter.VIEW_TYPE_ACTIVITY;
}
/** One type is normal data row, the other type is Progressbar */
#Override
public int getViewTypeCount() {
return 2;
}
/** the size of the List plus one, the one is the last row, which displays a
* Progressbar */
#Override
public int getCount() {
return Integer.MAX_VALUE;
}
/** return the type of the row, the last row indicates the user that the ListView is
* loading more data */
#Override
public int getItemViewType(int position) {
return mItems.containsKey(position
- EndlessScrollBaseAdapter.VIRTUAL_MIDDLE_OFFSET) ? EndlessScrollBaseAdapter.VIEW_TYPE_ACTIVITY
: EndlessScrollBaseAdapter.VIEW_TYPE_LOADING;
}
#Override
public T getItem(int position) {
return mItems.get(position - EndlessScrollBaseAdapter.VIRTUAL_MIDDLE_OFFSET);
}
#Override
public long getItemId(int position) {
return position;
}
/** returns the correct view */
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == EndlessScrollBaseAdapter.VIEW_TYPE_LOADING) {
return getFooterView(position, convertView, parent);
}
return getDataRow(position, convertView, parent);
};
/** A subclass should override this method to supply the data row.
*
* #param position
* #param convertView
* #param parent
* #return */
public abstract View getDataRow(int position, View convertView, ViewGroup parent);
/** returns a View to be displayed in the last row.
*
* #param position
* #param convertView
* #param parent
* #return */
public View getFooterView(int position, View convertView, ViewGroup parent) {
if (position >= mServerListSize && mServerListSize > 0) {
// the ListView has reached the last row
TextView tvLastRow = new TextView(mContext);
tvLastRow.setHint("Reached the last row.");
tvLastRow.setGravity(Gravity.CENTER);
return tvLastRow;
} else {
TextView tvLastRow = new TextView(mContext);
tvLastRow.setHint("Loading...\n position: " + position);
tvLastRow.setGravity(Gravity.CENTER);
return tvLastRow;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int virtualPosition);
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
for (int i = -mVisibleThreshold; i < visibleItemCount + mVisibleThreshold; i++) {
int virtualPosition = firstVisibleItem
- EndlessScrollBaseAdapter.VIRTUAL_MIDDLE_OFFSET + i;
onLoadMore(virtualPosition);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
EndlessScrollAdapter.java
package com.example.endlessscrollinbothdirections;
import java.util.Map;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class EndlessScrollAdapter extends EndlessScrollBaseAdapter<Integer> {
public EndlessScrollAdapter(Activity activity, Map<Integer, Integer> list) {
super(activity, list);
}
#Override
public View getDataRow(int position, View convertView, ViewGroup parent) {
TextView TextView;
if (convertView == null) {
TextView = new TextView(mContext);
} else {
TextView = (TextView) convertView;
}
TextView.setText("virtualPosition: "
+ (position - EndlessScrollBaseAdapter.VIRTUAL_MIDDLE_OFFSET) + "\n"
+ "row data: "
+ mItems.get(position - EndlessScrollBaseAdapter.VIRTUAL_MIDDLE_OFFSET));
return TextView;
}
#Override
public void onLoadMore(int virtualPosition) {
// here you might launch an AsyncTask instead
if (!mItems.containsKey(virtualPosition)) {
mItems.put(virtualPosition, virtualPosition);
notifyDataSetChanged();
}
}
}
MainActivity.java
package com.example.endlessscrollinbothdirections;
import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.lvItems);
Map<Integer, Integer> items = new HashMap<Integer, Integer>();
EndlessScrollAdapter endlessScrollAdapter = new EndlessScrollAdapter(this, items);
listView.setAdapter(endlessScrollAdapter);
listView.setSelection(EndlessScrollBaseAdapter.VIRTUAL_MIDDLE_OFFSET);
listView.setOnScrollListener(endlessScrollAdapter);
}
}
activity_main.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lvItems"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

Trying to create an app with an expandable list within a DrawerLayout

Trying to create an app with an expandable list within a DrawerLayout. I had the DrawerLayout working fine with just pulling the list from an array in strings.xml.
Ever since I added the ExpandableListAdapter though it's been crashing, or even if it runs it just doesn't let me do anything.
Here's my code:
package com.alpha.omegaRSS;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
public class MainActivity extends Activity {
private DrawerLayout navDrawerLayout;
private ActionBarDrawerToggle navDrawerToggle;
//private ListView navDrawerList;
private CharSequence navDrawerTitle;
private CharSequence navTitle;
private String[] leftItems;
private ExpandableListView navDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navTitle=navDrawerTitle=getTitle();
//leftItems = getResources().getStringArray(R.array.left_drawer_array);
navDrawerLayout=(DrawerLayout) findViewById(R.id.nav_layout);
//navDrawerList= (ListView) findViewById(R.id.left_drawer);
navDrawerList=(ExpandableListView)findViewById(R.id.left_drawer);
ArrayList<Parent> arrayParents = new ArrayList<Parent>();
ArrayList<String> arrayChildren = new ArrayList<String>();
//here we set the parents and the children
for (int i = 0; i < 10; i++){
//for each "i" create a new Parent object to set the title and the children
Parent parent = new Parent();
parent.setTitle("Parent " + i);
arrayChildren = new ArrayList<String>();
for (int j = 0; j < 10; j++) {
arrayChildren.add("Child " + j);
}
parent.setArrayChildren(arrayChildren);
//in this array we add the Parent object. We will use the arrayParents at the setAdapter
arrayParents.add(parent);
}
// set a custom shadow that overlays the main content when the drawer opens
navDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//set up the drawer's list view with items and click listener
navDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, leftItems));
// HERE I AM navDrawerList.setAdapter(new CustomListAdapter(MainActivity.this, arrayParents));
//navDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
navDrawerToggle=new ActionBarDrawerToggle(this, navDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close)
//called when the drawer is completely closed
{
public void onDrawerClosed(View mainView) {
getActionBar().setTitle(navTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(navDrawerTitle);
invalidateOptionsMenu();
}
};
navDrawerLayout.setDrawerListener(navDrawerToggle);
/*
//swiping controller
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
super.dispatchTouchEvent(event);
return gestureDetector.onTouchEvent(event);
}
SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float sensitvity = 50;
if ((e1.getX() - e2.getX()) > sensitvity) {
SwipeLeft();
} else if ((e2.getX() - e1.getX()) > sensitvity) {
SwipeRight();
}
return true;
}
};
GestureDetector gestureDetector = new GestureDetector(this,
simpleOnGestureListener);
*/
}
/* if(savedInstanceState==null){
selectItem(0);
}*/
#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) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (navDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
/*private void SwipeLeft() {
navDrawerLayout.closeDrawer(Gravity.RIGHT);
}
private void SwipeRight() {
navDrawerLayout.openDrawer(Gravity.LEFT);
}
*/
}
And here's my ExpandedlistAdapter class.
package com.alpha.omegaRSS;
import java.util.ArrayList;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
Import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.TextView;
public class CustomListAdapter extends BaseExpandableListAdapter {
private LayoutInflater inflater;
private ArrayList<Parent> mParent;
public CustomListAdapter(Context context, ArrayList<Parent> parent){
mParent = parent;
inflater = LayoutInflater.from(context);
}
#Override
//counts the number of group/parent items so the list knows how many times calls getGroupView() method
public int getGroupCount() {
return mParent.size();
}
#Override
//counts the number of children items so the list knows how many times calls getChildView() method
public int getChildrenCount(int i) {
return mParent.get(i).getArrayChildren().size();
}
#Override
//gets the title of each parent/group
public Object getGroup(int i) {
return mParent.get(i).getTitle();
}
#Override
//gets the name of each item
public Object getChild(int i, int i1) {
return mParent.get(i).getArrayChildren().get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
ViewHolder holder = new ViewHolder();
holder.groupPosition = i;
if (view == null) {
view = inflater.inflate(R.id.left_drawer, viewGroup,false);
}
TextView textView = (TextView) view.findViewById(R.layout.list_item_parent);
//"i" is the position of the parent/group in the list
textView.setText(getGroup(i).toString());
view.setTag(holder);
//return the entire view
return view;
}
#Override
//in this method you must set the text to see the children on the list
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
ViewHolder holder = new ViewHolder();
holder.childPosition = i1;
holder.groupPosition = i;
if (view == null) {
view = inflater.inflate(R.layout.drawer_list_item, viewGroup,false);
}
TextView textView = (TextView) view.findViewById(R.id.child_item);
//"i" is the position of the parent/group in the list and
//"i1" is the position of the child
textView.setText(mParent.get(i).getArrayChildren().get(i1));
view.setTag(holder);
//return the entire view
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
/* used to make the notifyDataSetChanged() method work */
super.registerDataSetObserver(observer);
}
/* #Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder)view.getTag();
if (view.getId() == holder.button.getId()){
// DO SOMETHING
}
}*/
protected class ViewHolder {
protected int childPosition;
protected int groupPosition;
protected Button button;
}
}
#Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
ViewHolder holder = new ViewHolder();
holder.groupPosition = i;
if (view == null) {
// You're inflating a id instead of a layout
// you should inflate your R.layout.[drawer_group_list_item]
view = inflater.inflate(R.id.left_drawer, viewGroup,false);
}
Let me know if this solve it!

Categories