I'm creating an android application and I have an activity with a android.support.design.widget.TabLayout and a ViewPager in it .
here is my code
activity_main.xml
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/cards_grouping_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabs" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
#BindView(R.id.tabs)
TabLayout tabs;
#BindView(R.id.cards_grouping_pager)
ViewPager pager;
private ArrayList<Category> categories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_cards);
ButterKnife.bind(this);
categories = //getDataFromApi
doSomeWorks();
}
private void doSomeWorks() {
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), categories);
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
LinearLayout tabStrip = (LinearLayout) tabs.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
final int finalI = i;
tabStrip.getChildAt(i).setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//I SHOULD SHOW POPUP HERE
}
});
}
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final ArrayList<String> TITLES = new ArrayList<>();
MyPagerAdapter(FragmentManager fm, ArrayList<Category> categories) {
super(fm);
for (int i = 0; i < categories.size(); i++) {
TITLES.add(categories.get(i).name);
}
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES.get(position);
}
#Override
public int getCount() {
return TITLES.size();
}
#Override
public Fragment getItem(int position) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return HorizontalTabsAdapter.newInstance(position, categories, displayMetrics.widthPixels,
displayMetrics.heightPixels);
}
}
}
I want to when user long click on each tab a popup appear exactly in selected position .
like below picture
How can I do that?
(not enough credits to comment, so posting as answer)
To implement long press clicklistener on each tab of tablayout, follow these answers
https://stackoverflow.com/a/43522131/6387236
https://stackoverflow.com/a/34982710/6387236
For the implementation of Popup Window at the location of long press, follow this nice blog,
https://rajeshandroiddeveloper.blogspot.in/2013/07/android-popupwindow-example-in-listview.html
Hope this helps
Related
I want to create a image slider in my application. A slider will contain around 6 images and user can swipe through them. if user does not interact it will swipe on its own in certain time interval.. I want to create 3 of such sliders in a single fragment.
what's the best approach for such design? three independent sliders. and of course I have to use as less memory possible..
Is there any library I should use.. please suggest the most optimized approach.
Thank you
You can use a ViewPager with views rather than fragments.
Check out this tutorial on how to use the ViewPager with views:
https://www.bignerdranch.com/blog/viewpager-without-fragments/
To scroll automatically use a timer and then call:
viewPager.setCurrentItem(1)
Where 1 is the second item etc...
If you wanna to use most optimized approach then you should use this Library for Image Slider,and there are full implementation is given so you can understand and use it easily.
But if you wanna to use only simple ViewPager then refer this site.In this tutorial there is simple implementation of ImageSlider is given.
Hope you get your answer,
Thanks.
add code in xml for slider
<RelativeLayout
android:id="#+id/cardView_adv_Slider_surchbuses_fragment"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginBottom="#dimen/margin_10"
android:background="#drawable/bg_shadow_transperent_rounded"
>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/margin_10"
android:background="#color/transparent"
android:gravity="center"
android:orientation="horizontal"></LinearLayout>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="#dimen/margin_5"
android:background="#drawable/btn_bg_white_rounded"
android:text="Exp - 29 Oct, 2018"
android:textColor="#color/colorGreen"
android:textStyle="bold" />
</RelativeLayout>
Add these methods in onCreate method
//To show slider of images-------------
SetAdViewPager();
SetDummyDataToImage();
Here I have added dummy data in arraylist.. you have to add ur data in arraylist
private void SetDummyDataToImage() {
PostImageModel postImageModel = new PostImageModel();
postImageModel.setImage("fbhgdkfjvbg/5c024b2c86b4c.jpg");
ImageList.add(postImageModel);
PostImageModel postImageModel1 = new PostImageModel();
postImageModel1.setImage("coecureiou/5c0130b533cca.jpg");
ImageList.add(postImageModel1);
PostImageModel postImageModel2 = new PostImageModel();
postImageModel2.setImage("fgvomtig/5c0130c67dbac.jpg");
ImageList.add(postImageModel2);
PostImageModel postImageModel3 = new PostImageModel();
postImageModel3.setImage("frejtufgi/5c01309d3ca33.jpg");
ImageList.add(postImageModel3);
NUM_PAGES = ImageList.size();
viewPager.getAdapter().notifyDataSetChanged();
myViewPagerAdapter.notifyDataSetChanged();
// viewPager.setAdapter(myViewPagerAdapter);
addBottomDots(0);
SetSliderAutoTimer();
}
private void SetAdViewPager() {
ImageList = new ArrayList<>();
myViewPagerAdapter = new MyViewPagerAdapter(ImageList);
viewPager.setSaveFromParentEnabled(false);
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[ImageList.size()];
layoutDots.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(Constants.mDashboardActivity);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(Constants.mDashboardActivity.getResources().getColor(R.color.colorGray));
layoutDots.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(Constants.mDashboardActivity.getResources().getColor(R.color.colorText));
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private ArrayList<PostImageModel> adsModelArrayList;
public MyViewPagerAdapter(ArrayList<PostImageModel> madsModelArrayList) {
adsModelArrayList = madsModelArrayList;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.row_post_image, container, false);
ImageView imgAd = view.findViewById(R.id.imgAd);
Picasso.get().load(adsModelArrayList.get(position).getImage()).into(imgAd);
container.addView(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(adsModelArrayList.get(position).getLink()));
startActivity(browserIntent);*/
}
});
return view;
}
#Override
public int getCount() {
return adsModelArrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
//Method to set timer to slider
private void SetSliderAutoTimer() {
final Handler handler = new Handler();
final Runnable update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
try {
viewPager.setCurrentItem(currentPage++, true);
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Timer().schedule(new TimerTask() {
#Override
public void run() {
handler.post(update);
}
}, 100, 5000);
}
private LinearLayout dotsLayout;
private TextView[] dots;
ArrayList<BannerModel> BannerArrayList;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
int currentPage = 0, NUM_PAGES = 0;
Timer timer;
Add this in oncreate
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
viewPager = (ViewPager) findViewById(R.id.view_pager_banner);
BannerArrayList = new ArrayList<>();
SetAdViewPager();
//Call this in webservice response .. now i m setting dummy data ------------------------------------------
//Add data in arraylist
for (int i = 0; i < 6; i++) {
BannerModel bannerModel = new BannerModel();
//Add your data here in model
BannerArrayList.add(bannerModel);
}
NUM_PAGES = BannerArrayList.size();
viewPager.getAdapter().notifyDataSetChanged();
myViewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(myViewPagerAdapter);
addBottomDots(0);
SetSliderAutoTimer();
//---------------------------------------------------------------------------
Add these methods
//Method to set timer to slider
private void SetSliderAutoTimer() {
Log.e("SetSliderAutoTimer", "SetSliderAutoTimer");
final Handler handler = new Handler();
final Runnable update = new Runnable() {
public void run() {
Log.e("update", "update");
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(update);
}
}, 100, 6000);
}
//Set viepager and adapter
private void SetAdViewPager() {
myViewPagerAdapter = new MyViewPagerAdapter(BannerArrayList);
viewPager.setSaveFromParentEnabled(false);
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
//Method to set dots according to slider position
private void addBottomDots(int currentPage) {
dots = new TextView[BannerArrayList.size()];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(SetLocationActivity.this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(50);
dots[i].setTextColor(SetLocationActivity.this.getResources().getColor(R.color.colorGray));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(SetLocationActivity.this.getResources().getColor(R.color.colorText));
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private ArrayList<BannerModel> bannerModelArrayList;
public MyViewPagerAdapter(ArrayList<BannerModel> mbannerModelArrayList) {
bannerModelArrayList = mbannerModelArrayList;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.row_banner, container, false);
ImageView imgAd = view.findViewById(R.id.imgAd);
Picasso.get().load(bannerModelArrayList.get(position).getImage()).into(imgAd);
container.addView(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return view;
}
#Override
public int getCount() {
return bannerModelArrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
xml is as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sweedesi.android.customerapp.SetLocationActivity">
<android.support.v7.widget.CardView
android:id="#+id/cardView_adv_Slider_surchbuses_fragment"
android:layout_width="match_parent"
android:layout_height="250dp"
app:cardBackgroundColor="#color/colorWhite"
app:cardElevation="#dimen/margin_10">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager_banner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal"></LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I'm trying to update textview in fragment from another activity. But I'm getting a NUllPointerException when calling the setText method. I have tried the following, but still getting the NPE.
1. Tried accessing the fragments textview with FindViewbyId in activity.
2. Tried using a method in fragment and calling it from activity and passing the value as parameters
FragHome Activity
public class FragHome extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
Handler bluetoothIn;
private static TextView tmpF, humF, CoF;
String tempGL, HumGL, coGL, devname;
double dblTemp, dblCo;
final int handlerState = 0; // used to identify handler message
private BluetoothAdapter btAdapter = null;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_home);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Temperature"));
tabLayout.addTab(tabLayout.newTab().setText("Humidity"));
tabLayout.addTab(tabLayout.newTab().setText("CO"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
bluetoothIn=new Handler() {
String readMessage;
String[] values = new String[]{""};
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
readMessage = (String) msg.obj;
values = readMessage.split("#");
for (int j = 0; j < values.length; j++) {
int rem = j % 3;
if (rem == 0) {
tmpF.setText(values[j] + " C");
tempGL = String.valueOf(values[j]);
try {
dblTemp = Double.parseDouble(tempGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 1) {
CoF.setText(values[j] + " ppm");
coGL = values[j];
try {
dblCo = Double.parseDouble(coGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 2) {
humF.setText(values[j] + " %");
HumGL = values[j];
}
}
}
}
};
btAdapter=BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
// mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Pager
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Tab1
public class OneFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
fragment_one.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="shinil.tablayout.OneFragment"
android:id="#+id/rltnvnv">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/textviewtemp"
android:layout_centerInParent="true"/>
</RelativeLayout>
frag_home.xml
LinearLayout
android:id="#+id/main_layout"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- our toolbar -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The NPE occurs when I try to settext from the activity. Please help
Use below callback:
Fragment Class:
public class FragmentOne extends Fragment {
private ViewCallback mCallback;
public FragmentOne(ViewCallback mCallback) {
this.mCallback = mCallback;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
mCallback.updateTextView((TextView) view.findViewById(R.id.fragmentTextView));
return view;
}
public interface ViewCallback {
void updateTextView(TextView view);
}
}
Below is the Activity class:
public class MainCallbackActivity extends Activity implements CallbackFragment.ViewCallback {
public TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callback);
FragmentOne fragment = new FragmentOne(this);
getFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();
}
#Override
protected void onResume() {
super.onResume();
if (textView != null)
textView.setText("Updating Fragment TextView in Activity..!!");
}
#Override
public void updateTextView(TextView view) {
this.textView = view;
}
}
Implment that call back in your activity class..then update the textview.
I have a problem with implementing custom tabs, and I know i could've just used the setCompoundDrawablesWithIntrinsicBounds for just TextView in my Layout file, but I need to show 2 another ImageViews in one Layout file.I have a custom layout for it, which I inflate like this:
public class TabsAdapter extends FragmentPagerAdapter {
private int mPageCount;
private Context mContext;
private int[] stringResID = { R.string.serverString, R.string.localString, R.string.commonString, R.string.searchString };
private int[] imagesResID = { R.drawable.tab1, R.drawable.tab2, R.drawable.tab3, R.drawable.tab4};
public TabsAdapter(FragmentManager fm, int pageCount, Context context) {
super(fm);
mPageCount = pageCount;
mContext = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab, null);
TextView tv = (TextView) view.findViewById(R.id.titleTab);
tv.setText(stringResID[position]);
ImageView img = (ImageView) view.findViewById(R.id.tabImage);
img.setImageDrawable(ContextCompat.getDrawable(mContext, imagesResID[position]));
return view;
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return mPageCount;
}
}
And my layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/titleTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ololo"
android:layout_centerInParent="true"/>
<ImageView
android:id="#+id/tabImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_above="#+id/titleTab"/>
</RelativeLayout>
And call it from MainActivity like this:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
TabsAdapter pagerAdapter =
new TabsAdapter(getSupportFragmentManager(), 4,MainActivity.this);
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if(tab != null) {
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
So here's the question: what am I doing wrong? Becaus this code just gives me text in tabs, without ImageView. Please help if you tried to do something like this.
I'm following a tutorial to get icons in a tab bar made by the ViewPagerIndicator library, but they don't show up. The titles appear, and the getIconsResId method gets called, but nevertheless the icons can't be seen.
This is the code I use for my PageAdapter class. It is almost an exact copy of the sample file in the library.
public class IconsPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", };
protected static final int[] ICONS = new int[] {
R.drawable.guest,
R.drawable.home,
R.drawable.group,
R.drawable.leaderboard
};
private int mCount = CONTENT.length;
public IconsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ViewItemTabsActivity.PlaceholderFragment.newInstance(position+1);
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
System.out.println("Got called");
return IconsPagerAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
System.out.println("This one also got called");
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
This is the code I have written to create the adapter and the indicator:
mSectionsPagerAdapter = new IconsPagerAdapter(faActivity.getSupportFragmentManager());
mViewPager.setAdapter((PagerAdapter) mSectionsPagerAdapter);
TabPageIndicator titleIndicator = (TabPageIndicator)llLayout.findViewById(R.id.titles);
titleIndicator.setViewPager(mViewPager);
Any help would be much appreciated.
EDIT
Here is the XML for the llLayout variable. Note that it isn't actually a linear layout, but a ViewPager (I know that it isn't a brilliant name for the variable).
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.groupproject.sharingapp.ViewItemTabsActivity">
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/titles"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
</android.support.v4.view.ViewPager>
I've looked at the samples and the only difference seems to be the name, but when I just switch all the names in my app to TabPageIndicator from TitlePageIndicator, the tabs are in a messed up alignment and the footer underline is gone.
Am I missing something? Is there something extra I need to do? I have
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter( getSupportFragmentManager() );
ViewPager pager =
(ViewPager)findViewById( R.id.viewpager );
TabPageIndicator indicator =
(TabPageIndicator)findViewById( R.id.indicator );
pager.setAdapter( adapter );
indicator.setViewPager( pager );
and
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
What are the differences between TabPageIndicator and TitlePageIndicator?
Try viewing that page and see if you find the answer.
I did, that's why I posted to begin with.
Title Indicator
Displays the title of the selected page in the center with the titles
of the adjacent pages (if available) in a more subtle style.
Tab Indicator
Similar to the title indicator but displays as many titles as possible
in scrolling and animated horizontal tabs.
TitlePagerIndicator example:
Adapter
class TestFragmentAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", };
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
When you use TitlePagerIndicator you need to implement TitleProvider in your Adapter.
class TestTitleFragmentAdapter extends TestFragmentAdapter implements TitleProvider {
public TestTitleFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public String getTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
}
Putting it all together
TestFragmentAdapter mAdapter = new TestTitleFragmentAdapter(getSupportFragmentManager());
ViewPager mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
PageIndicator mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
TabPagerIndicator example:
public class SampleTabsDefault extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres" };
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
mAdapter = new GoogleMusicAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class GoogleMusicAdapter extends TestFragmentAdapter implements TitleProvider {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
#Override
public int getCount() {
return SampleTabsDefault.CONTENT.length;
}
#Override
public String getTitle(int position) {
return SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length].toUpperCase();
}
}
}
All of these examples and more can be found on Jake Wharton's Github repo for ViewPagerIndicator