I am trying to find a way to change text size of Tab Title when selected. Until now without exit. Hope someone can help me.
My code bellow:
XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab_layout"
app:tabSelectedTextColor="#android:color/holo_orange_dark"
app:tabTextAppearance="#style/textAppearance">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager_view"/>
Style used for tabTextAppearance:
<style name="textAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">18sp</item>
<item name="android:textStyle">bold</item>
</style>
My adapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final Resources resources;
private static final int num = 3;
public ViewPagerAdapter(FragmentManager fm, Resources resources) {
super(fm);
this.resources = resources;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentA();
break;
case 1:
fragment = new FragmentB();
break;
case 2:
fragment = new FragmentC();
break;
}
return fragment;
}
#Override
public int getCount() {
return num;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
switch (position) {
case 0:
title = "A";
break;
case 1:
title = "B";
break;
case 2:
title = "C";
break;
}
return title;
}
}
And My Carousel Fragment class:
public class CarouselFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_carousel, container, false);
tabLayout = (TabLayout)root.findViewById(R.id.tab_layout);
viewPager = (ViewPager)root.findViewById(R.id.pager_view);
setHasOptionsMenu(true);
return root;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), getResources());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setSelectedTabIndicatorColor(Color.RED);
tabLayout.setupWithViewPager(viewPager);
}else {
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here i should do something, but what???
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//here i should do something, but what???
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
Many thanks in advance!
use this code
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
TextView tabTextView = new TextView(this);
tab.setCustomView(tabTextView);
tabTextView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
tabTextView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
tabTextView.setText(tab.getText());
if (i == 0) {
tabTextView.setTextSize(16);
}
}
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
ViewGroup vgTab = (ViewGroup) vg.getChildAt(tab.getPosition());
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTextSize(16);
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
ViewGroup vgTab = (ViewGroup) vg.getChildAt(tab.getPosition());
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTextSize(14);
}
}
}
}
I would recommend to set custom tab.
First you need to initiate your custom tabs, otherwise it won't change anything.
Create a new layout with a TextView (you can add whatever you want to be in each tab).
In your onActivityCreated after your tabLayout.setupWithViewPager initiate your custom tabs:
for (int i = 0; i < 3; i++) { // 3 - A+B+C in your example
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
ViewGroup tabContainer = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.custom_tab_item, tabLayout, false);
if (tabContainer != null) {
TextView yourTv = (TextView) tabContainer.findViewById(R.id.tv);
yourTv.setTextSize(18);
tab.setCustomView(tabContainer);
}
}
}
Add listener tabLayout.addOnTabSelectedListener and Implement TabLayout.OnTabSelectedListener, In your onTabSelected use this:
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
View customView = tab.getCustomView();
if (customView != null) {
TextView yourTv = (TextView) customView.findViewById(R.id.tv);
if (yourTv != null) {
if (i == selectedTabIndex) {
yourTv.setTextSize(18);
} else {
yourTv.setTextSize(16);
}
}
}
}
}
You can set your own view to the TabLayout's individual tabs and you can change the size latter on the tab selection-
Here is the code hint -
TabLayout mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
TabLayout.Tab tabOne = mTabLayout.newTab();
tabOne.setCustomView(getLayoutInflater().inflate(R.layout.item_tab, mTabLayout, false));
mTabLayout.addTab(tabOne);
TabLayout.Tab tabTwo = mTabLayout.newTab();
tabTwo.setCustomView(getLayoutInflater().inflate(R.layout.item_tab, mTabLayout, false));
mTabLayout.addTab(tabTwo);
tabTwo.select();
// mTabLayout.setupWithViewPager(mViewPager);
if (getResources().getDisplayMetrics().widthPixels > getResources().getDisplayMetrics().heightPixels) {
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
} else {
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
((TextView) tab.getCustomView().findViewById(R.id.text1)).setTextSize(16);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
((TextView) tab.getCustomView().findViewById(R.id.text1)).setTextSize(13);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
iteb_tab.xml can be like -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="One"
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
You can further synchronize the selection with viewpager page change as
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mTabLayout.getTabAt(position).select();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Edit
You can further reduce your effort by setting your tab titles from the adapter itself -
PagerAdapter mPagerAdapter = mViewPager.getAdapter();
for (int position = 0; position < mPagerAdapter.getCount(); position++) {
View view = (getLayoutInflater().inflate(R.layout.item_tab, mTabLayout, false));
TextView label = (TextView) view.findViewById(R.id.text1);
label.setText(mPagerAdapter.getPageTitle(position));
TabLayout.Tab tab = mTabLayout.newTab();
tab.setCustomView(view);
mTabLayout.addTab(tab);
}
Here is how it looks -
Related
I am using a view pager in my app the view pager contains three layouts and I can swipe between them well and it shows me the different layout files but when I tried to use java orders on this layout I found that nothing changed in the layout for example I tried to change the text of a textView but I found that it hasn't changed
this is the main activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
and this is the java code of the fragment :
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View myView = inflater.inflate(R.layout.fragment_home, container, false);
etAddPost = myView.findViewById(R.id.etAddPost);
TextView tv = myView.findViewById(R.id.testText);
tv.setText("new text");
addPostBtn(myView);
return myView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
and this is the view pager adapter code :
public class SamplePagerAdapter extends PagerAdapter {
Context context;
public SamplePagerAdapter(Context context) {
this.context = context;
}
/**
* #return the number of pages to display
*/
#Override
public int getCount() {
return 3;
}
/**
* #return true if the value returned from {#link #instantiateItem(ViewGroup, int)} is the
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
// BEGIN_INCLUDE (pageradapter_getpagetitle)
/**
* Return the title of the item at {#code position}. This is important as what this method
* <p>
* Here we construct one using the position value, but for real application the title should
* refer to the item's contents.
*/
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "تعلم";
break;
case 1:
title = "الصفحة الرئيسية";
break;
case 2:
title = "التحديات";
break;
}
return title;
}
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at {#code position}. Here we
* inflate a layout from the apps resources and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
// Inflate a new layout from our resources
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert li != null;
View view = null;
switch (position) {
case 0:
view = li.inflate(R.layout.fragment_learn, container, false);
break;
case 1:
view = li.inflate(R.layout.fragment_home, container, false);
break;
case 2:
view = li.inflate(R.layout.fragment_challenges, container, false);
break;
}
// Add the newly created View to the ViewPager
container.addView(view);
// Return the View
return view;
}
/**
* {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
and this is the activity main xml code :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
I am creating an application with dynamic tabs. I created tabs are able to add tabs by clicking a button and are able to remove from the back. But when I tried to remove the first tab, it is removed while after removing the first tab and tried to delete the last tab it is force closing with out-of-bounds exception.
I figure out the issue. Suppose there are 4 TABS and when I tried to delete the first tab 0th position tab (TAB 1) is deleted, now when I tried to delete the last tab say now the 4th TAB tab(now Supposedly 2nd position) it crashes as when I tried to log the position on deleting it shows the position as 3rd position.
ALl the deleting is done from viewPage adapter. and the code is :
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
Log.e("REMOVING POSITION ",String.valueOf(position));
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
Log.e("mFragmentList_REMOVE",String.valueOf(mFragmentList.size()));
Log.e("TitleList_REMOVE",String.valueOf(mFragmentTitleList.size()));
removeTab(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
}
public View getTabView(final int position) {
Log.e("mFragmentList",String.valueOf(mFragmentList.size()));
Log.e("TitleList",String.valueOf(mFragmentTitleList.size()));
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
CircleImageView tabItemAvatar =
(CircleImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
Log.e("getCount()-MAIN",String.valueOf(getCount()));
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
ImageButton add = (ImageButton) view.findViewById(R.id.imageButtonAdd);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("getCount()-ADD",String.valueOf(getCount()));
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+position);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
addFrag(fragmentChild, "POS"+position);
notifyDataSetChanged();
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void destroyFragmentView(ViewGroup container, int position, Object object) {
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
notifyDataSetChanged();
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
}
viewPager.setAdapter(this);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
TAB STYLE:
Please help me to sort out this issue! what am i doing wrong here.I used a tutorial and done exactly as explained.
FINALLY FOUND A SOLUTION
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
added this piece of code to removeFrag function!
public void removeFrag(int position) {
removeTab(position);
Log.e("REMOVING POSITION ",String.valueOf(position));
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
Log.e("mFragmentList_REMOVE",String.valueOf(mFragmentList.size()));
Log.e("TitleList_REMOVE",String.valueOf(mFragmentTitleList.size()));
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
}
Use this function to remove..this is happening because :-
The position of your getView(int position) is not updated after you are removing a tab.. so write the function of click listener of remove(imageButton) like this..
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
remove.setEnabled(false); // it here..
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
public void removeFrag(int position) {
Log.e("REMOVING POSITION ",String.valueOf(position));
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
Log.e("mFragmentList_REMOVE",String.valueOf(mFragmentList.size()));
Log.e("TitleList_REMOVE",String.valueOf(mFragmentTitleList.size()));
removeTab(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
setupTabLayout(); // do the setup of tablayout after removing
}
Edit Do one more thing dont forget to disable the button.. because if the user clicks the button two consecutive times..in a flash the might crash..
remove.setEnabled(false); disable and enable again at getView(int position) again..
getView(int position)
{
........
remove.setEnabled(true); //enable
}
Update :-
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
//notifyDataSetChanged(); //notify here
removeTabPage(position);
}
//viewPager.setAdapter(this);
}
You also need to remove the page..
public void removeTabPage(int position) {
if (!mFragmentList.isEmpty() && position<mFragmentList.size()) {
mFragmentList.remove(position);
notifyDataSetChanged();
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
notifyDataSetChanged();
viewPager.setAdapter(this);
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
CircleImageView tabItemAvatar =
(CircleImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
removeFrag(position);
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
switch (mFragmentTitleList.get(position)) {
case "Gaiduk":
tabItemAvatar.setImageResource(R.drawable.gaiduk);
break;
case "Nguyen":
tabItemAvatar.setImageResource(R.drawable.avatar);
break;
case "Balakin":
tabItemAvatar.setImageResource(R.drawable.balakin);
break;
case "Golovin":
tabItemAvatar.setImageResource(R.drawable.golovin);
break;
case "Ovcharov":
tabItemAvatar.setImageResource(R.drawable.ovcharov);
break;
case "Solovienko":
tabItemAvatar.setImageResource(R.drawable.solovei);
break;
default:
tabItemAvatar.setImageResource(R.drawable.boy);
break;
}
return view;
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0) {
tabLayout.removeTabAt(position);
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Added removeFrag function as:
public void removeFrag(int position) {
removeTab(position);
Log.e("REMOVING POSITION ",String.valueOf(position));
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
Log.e("mFragmentList_REMOVE",String.valueOf(mFragmentList.size()));
Log.e("TitleList_REMOVE",String.valueOf(mFragmentTitleList.size()));
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
}
I Have a fragment in which I have a list view this is my layout :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dip"
android:drawSelectorOnTop="false"
android:visibility="visible" />
</FrameLayout>
Next I create a fragment (activity) :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_fragment_all_object, container,false);
listView = (ListView) view.findViewById(R.id.list);
Integer iloscObiektow = Singleton.getInstance().getListaODE().size();
int i, num_squares = iloscObiektow;
RowBean RowBean_data[] = new RowBean[num_squares];
for (i = 0; i < RowBean_data.length; i++) {
RowBean_data[i] = new RowBean(Singleton.getInstance().getListaODE().get(i).visible, Singleton.getInstance().getListaODE().get(i).name);
}
AllObjectAdapter a = new AllObjectAdapter(getActivity(),RowBean_data);
listView.setAdapter(a);
return view;
}
And this is my AllObjectAdapter :
public class AllObjectAdapter extends BaseAdapter {
private LayoutInflater inflater;
private RowBean data[];
public AllObjectAdapter(Context context, RowBean[] data) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.data = data;
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return data[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
RowBean rowBean = data[position];
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.all_object_holder, null);
holder.name = (TextView) view.findViewById(R.id.showText);
holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
}else {
holder = (ViewHolder) view.getTag();
}
holder.name.setText(rowBean.getTitle());
return null;
}
public class ViewHolder {
CheckBox checkBox;
TextView name;
}
}
I have a fragment and an activity . I want to display name of tags(fragments) but I don't want to show name of application in actionBar : this is my activity : When I remove a ActionBarActivity I can not use a FragmentManager
public class ObjectListActivity extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener {
private ViewPager viewPager;
private android.support.v7.app.ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_object_list2);
// View pager for showing many fragments over a single activity
viewPager = (ViewPager) findViewById(R.id.pager);
// Getting fragment manager to control fragments
FragmentManager fragmnetManager = getSupportFragmentManager();
// Setting adapter over view pager
viewPager.setAdapter(new MyAdapter(fragmnetManager));
// Implementing view pager pagechangelistener to navigate between tabs
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
// Setting navigation of tabs to actionbar
actionBar.setSelectedNavigationItem(pos);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
// Getting actionbar
actionBar = getSupportActionBar();
// Setting navigation mode to actionbar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Now adding a new tab to action bar and setting title, icon and
// implementing listener
android.support.v7.app.ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("Wszytskie");
// tab1.setIcon(R.drawable.ic_launcher);
tab1.setTabListener(this);
android.support.v7.app.ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Grupy");
tab2.setTabListener(this);
// Now finally adding all tabs to actionbar
actionBar.addTab(tab1);
actionBar.addTab(tab2);
}
#Override
public void onTabReselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
FragmentTransaction arg1) {
// Setting current position of tab to view pager
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
// Getting fragments according to selected position
Fragment fragment = null;
if (i == 0) {
fragment = new FragmentAllObjectActivity();
}
if (i == 1) {
fragment = new FragmentGroupObjectsActivity();
}
// and finally returning fragments
return fragment;
}
#Override
public int getCount() {
// Returning no. of counts of fragments
return 2;
}
}
your are returning null in your getView() method of the adapter
Change it to return the view object
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
RowBean rowBean = data[position];
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.all_object_holder, null);
holder.name = (TextView) view.findViewById(R.id.showText);
holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
}else {
holder = (ViewHolder) view.getTag();
}
holder.name.setText(rowBean.getTitle());
return view; //change here
}
To remove actionbar use:
// Getting actionbar
actionBar = getSupportActionBar();
actionBar.hide(); //add this
I have a tablayout, from android design support library:
compile 'com.android.support:design:23.0.1'
With this, I want to populate my tabs. But I'm failing to do that. I can create the tabs, but they fail to inflate their respective content:
Where it should have entries from LinearListView, an object similar to a ListView imported from this framework:
compile 'com.github.frankiesardo:linearlistview:1.0.1#aar'
I tried a great number of examples, but I failed to populate each tab. Any suggestions?
Code:
JAVA:
From main fragment:
OverviewTabLayoutPagerAdapter adapter = new OverviewTabLayoutPagerAdapter(getActivity().getSupportFragmentManager(), productDataContent, getContext());
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
OverviewTabLayoutPagerAdapter:
public class OverviewTabLayoutPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "REVIEWS", "VIDEOS", "DEALS" };
private SearchContent productDataContent;
private Context context;
public OverviewTabLayoutPagerAdapter(FragmentManager fm, SearchContent productDataContent, Context context) {
super(fm);
this.productDataContent = productDataContent;
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
Log.i("TAB_POSITION", String.valueOf(position));
if (position == 0) {
return OverviewTab1Fragment.newInstance(position, productDataContent);
} else if (position == 1) {
return OverviewTab2Fragment.newInstance(position, productDataContent);
} else if (position == 2) {
return OverviewTab3Fragment.newInstance(position, productDataContent);
}
return OverviewTab1Fragment.newInstance(position, productDataContent);
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
OverviewTab*Fragment: (the * means the same code structure applies for every fragment):
public class OverviewTab*Fragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
public static final String PRODUCT_DATA_CONTENT = "PRODUCT_DATA_CONTENT";
private int mPage;
private SearchContent productDataContent;
public static OverviewTab*Fragment newInstance(int page, SearchContent productDataContent) {
OverviewTab*Fragment fragment = new OverviewTab*Fragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
args.putSerializable(PRODUCT_DATA_CONTENT, productDataContent);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
productDataContent = (SearchContent) getArguments().getSerializable(PRODUCT_DATA_CONTENT);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.overview_tab_fragment, container, false);
LinearListView tabContentListView = (LinearListView) view.findViewById(R.id.product_content_linear_list_view);
populateOverviewTab*LinearLayout(tabContentListView, productDataContent);
return view;
}
private void populateOverviewTab*LinearLayout(LinearListView tabContentListView, SearchContent productDataContent) {
ArrayList<> productData = productDataContent.getContent();
OverviewTab*ArrayAdapter overviewTab*ArrayAdapter = new OverviewVideosArrayAdapter(
getContext(),
tabContentListView,
productData,
getActivity()
);
tabContentListView.setAdapter(overviewTab*ArrayAdapter);
...
XML:
From main fragment:
...
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/go_to_store_button"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
...
overview_tab_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.linearlistview.LinearListView
android:id="#+id/product_content_linear_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:showDividers="end"
android:dividerPadding="5dp"
app:dividerThickness="2dp">
</com.linearlistview.LinearListView>
</RelativeLayout>
You can change:
#Override
public Fragment getItem(int position) {
Log.i("TAB_POSITION", String.valueOf(position));
if (position == 0) {
return OverviewTab1Fragment.newInstance(position, productDataContent);
} else if (position == 1) {
return OverviewTab2Fragment.newInstance(position, productDataContent);
} else if (position == 2) {
return OverviewTab3Fragment.newInstance(position, productDataContent);
}
return OverviewTab1Fragment.newInstance(position, productDataContent);
}
for this:
#Override
public Fragment getItem(int position) {
Log.i("TAB_POSITION", String.valueOf(position));
if (position == 0) {
return OverviewTab1Fragment.instantiate(context, productDataContent);
} else if (position == 1) {
return OverviewTab2Fragment.instantiate(context, productDataContent);
} else if (position == 2) {
return OverviewTab3Fragment.instantiate(context, productDataContent);
}
return OverviewTab1Fragment.instantiate(context, productDataContent);
}
UPDATE
This is an example with Fragment in Array:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;
public class TabsViewPagerAdapter extends FragmentStatePagerAdapter {
private CharSequence titlesArray[]; // This will Store the Titles of the Tabs which are Going to be passed when TabsViewPagerAdapter is created
private Fragment tabsArray[];
private SparseArray<Fragment> registeredFragments;
// Build a Constructor and assign the passed Values to appropriate values in the class
public TabsViewPagerAdapter(FragmentManager fm, CharSequence titlesArray[], Fragment[] tabsArray) {
super(fm);
this.titlesArray = titlesArray;
this.tabsArray = tabsArray;
this.registeredFragments = new SparseArray<>();
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
return tabsArray[position];
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return titlesArray[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return titlesArray.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
In the Java you create the adapter:
String[] tabTitles = new String[]{"Tab1", "Tab2", "Tab3"};
Fragment[] tabsArray = new Fragment[]{new OverviewTab1Fragment(), new OverviewTab2Fragment(), new OverviewTab3Fragment()};
adapter = new TabsViewPagerAdapter(getSupportFragmentManager(), tabTitles, tabsArray);
And the fragment is something like this:
import android.support.v4.app.Fragment;
public class OverviewTab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.yourFragmentLayout, container, false);
return v;
}
}
I hope help you.
i'm having some issues implementing a Sliding Tabs activity that contains 2 Fragments and a Swipe Down to Refresh layout, namely implementing the Swipe Down to Refresh part (the rest is working just fine).
First here are my XML files.
The Main Activity XML , which contains the ViewPager wrapped in an SwipeRefreshLayout :
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.popal.soul.MovieListActivityTEST">
<com.example.popal.soul.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</android.support.v4.widget.SwipeRefreshLayout>
And the first tab XML , one of the 2 tabs (both are similar, so i`ll only post one)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Now, my main activity, which handles the ViewPager, Adapter an the SlidingTabsLayout.
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// 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);
// 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);
}
And finally, my fragment for the first Tab
public class Tab1 extends Fragment {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
private SwipeRefreshLayout swipeContainer;
private List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
private ProgressBar progressBar;
private final static String MOVIES_POST_REQUEST ="//Long String, Edited out since it`s not relevant"
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
movieListAdaptor.clear();
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
swipeContainer.setRefreshing(false);
}
});
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
The issue is, i'm getting a NULL Pointer Exception at swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {...} method, which i guess is because the Swipe-to-Refresh layout is in the main activity XML, and not the tabs fragment. So what is the proper way to implement this ? I also tried implementing a Swipe to refresh layout in one of the Tabs XML instead of wrapping the ViewPager in it, like above, but it would crash when swiping from tab to another.
Here`s the code from the entire fragment in Tab1, for tobs answer below
public class MoviesTabFragment extends Fragment implements Refreshable {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
//private SwipeRefreshLayout swipeContainer;
public List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
public ProgressBar progressBar;
public final static String MOVIES_POST_REQUEST ="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
#Override
public void refresh() {
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
}
public class Send_data_to_server extends AsyncTask<String, Void, String> {
private String data_poster;
private String data_fanart;
// protected void onPreExecute() {
// progressBar.setVisibility(View.VISIBLE);
// }
protected String doInBackground(String... params)
{
String jason_data = params[0];
HttpClient http_con = new HttpClient();
String output_from_server = http_con.establish_con(jason_data);
Log.i("DataFromServer", output_from_server);
JSONObject json_Obj = null;
JSONObject child_obj = null; //creating the "result" object in the main JSON Object
try {
json_Obj = new JSONObject(output_from_server);
child_obj = create_subObject("result", json_Obj);
JSONArray jsonArray = child_obj.optJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title_data = jsonObject.optString("label").toString();
String plot_data = jsonObject.optString("plot").toString();
String year_data = jsonObject.optString("year").toString();
String movie_id_data = jsonObject.optString("movieid").toString();
String imdb_score = jsonObject.optString("rating").toString();
String imdb_score_short = imdb_score.substring(0, 3);
JSONObject child_obj2 = create_subObject("art", jsonObject);
data_poster = child_obj2.optString("poster").toString();
data_fanart = child_obj2.optString("fanart").toString();
JSONEncodePosterFanart encodePosterFanart = new JSONEncodePosterFanart();
String jason_dataPoster = encodePosterFanart.GetPosterFanartEncodedURL(data_poster);
String jason_dataFanart = encodePosterFanart.GetPosterFanartEncodedURL(data_fanart);
HttpClient http = new HttpClient();
String output_from_serverPoster = http.establish_con(jason_dataPoster);
HttpClient http2 = new HttpClient();
String output_from_serverFanart = http2.establish_con(jason_dataFanart);
JSONPosterFanart poster_fanart = new JSONPosterFanart();
String post_dl = poster_fanart.GetPosterFanart(output_from_serverPoster);
JSONPosterFanart poster_fanart2 = new JSONPosterFanart();
String fanart_dl = poster_fanart2.GetPosterFanart(output_from_serverFanart);
if (null == movieList) {
movieList = new ArrayList<MovieListAdapter.MovieDetails>();
}
MovieListAdapter.MovieDetails item = new MovieListAdapter.MovieDetails(title_data+" ("+year_data+")", post_dl, fanart_dl,plot_data,movie_id_data,imdb_score_short);
movieList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return output_from_server;
}
protected void onPostExecute(String output_from_server) {
super.onPostExecute(output_from_server);
//progressBar.setVisibility(View.INVISIBLE);
movieListAdaptor = new MovieListAdapter(getActivity(), movieList);
recycleList.setAdapter(movieListAdaptor);
}
private JSONObject create_subObject(String tagName, JSONObject jObj) throws JSONException {
JSONObject subObj = jObj.getJSONObject(tagName); //getJSONObject returns the value from tagName (in our case jason_Obj that is being passed ar a param)
return subObj;
}
}
}
And the RecycleView adapter:
public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MovieViewHolder> {
public List<MovieDetails> movieList;
private Context mContext;
public MovieListAdapter(Context mContext, List<MovieDetails> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public int getItemCount() {
return movieList.size();
}
public void clear() {
movieList.clear();
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout_movies_list, viewGroup, false);
return new MovieViewHolder(itemView);
}
#Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {
MovieDetails mdet = movieList.get(i);
String fanart = "http://192.168.1.128/"+mdet.getImageViewFanart();
String poster = "http://192.168.1.128/"+mdet.getImageViewPoster();
Log.i("fanart", fanart);
Log.i("poster", poster);
movieViewHolder.vTitle.setText(mdet.Title);
Picasso.with(mContext).load(poster)
.resize(500, 746)
.error(R.drawable.poster_placeholder)
.placeholder(R.drawable.poster_placeholder)
.into(movieViewHolder.vPoster);
Picasso.with(mContext).load(fanart)
.resize(960, 540)
.error(R.drawable.fanart_placeholder)
.placeholder(R.drawable.fanart_placeholder)
.into(movieViewHolder.vFanart);
movieViewHolder.vplot = mdet.getPlot();
movieViewHolder.vmovie_id = mdet.getMovie_id();
}
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView vTitle;
protected ImageView vPoster;
protected ImageView vFanart;
protected String vplot;
protected String vmovie_id;
protected String vimdb_score;
public MovieViewHolder(View v)
{
super(v);
vplot = new String();
vmovie_id = new String();
vimdb_score = new String();
vTitle = (TextView) v.findViewById(R.id.title);
vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
MovieDetails mov = movieList.get(position);
Intent intent = new Intent(mContext, MovieDetailsPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("movieid", mov.getMovie_id());
bundle.putString("plot", vplot);
bundle.putString("fanart_path", mov.getImageViewFanart());
bundle.putString("imdb_score", mov.getImdb_score());
intent.putExtras(bundle);
mContext.startActivity(intent);
}
}
public static class MovieDetails {
protected String Title;
protected String imageViewPoster;
protected String imageViewFanart;
protected String plot;
protected String movie_id;
protected String imdb_score;
public MovieDetails(String Title, String imageViewPoster,String imageViewFanart, String plot, String movie_id ,String imdb_score)
{
this.Title = Title;
this.imageViewPoster = imageViewPoster;
this.imageViewFanart = imageViewFanart;
this.plot = plot;
this.movie_id = movie_id;
this.imdb_score = imdb_score;
}
public String getTitle() {return Title;}
public String getImageViewPoster() {
return imageViewPoster;
}
public String getImageViewFanart() {
return imageViewFanart;
}
public String getPlot() {return plot;}
public String getMovie_id() {return movie_id;}
public String getImdb_score() {return imdb_score;}
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
MoviesTabFragment moviesTabFragment = new MoviesTabFragment();
return moviesTabFragment;
}
else
{
TVShowsTabFragment TVShowsTabFragment = new TVShowsTabFragment();
return TVShowsTabFragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
You're getting the NullPointerException because you inflate your fragment layout from R.layout.tab_1 which does not contain a SwipeRefreshLayout.
If you want the layout to be the parent of your ViewPager, I would recommend you to move your code which manages the RefreshLayout to the MainActivity:
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SwipeRefreshLayout refreshLayout;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// 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);
// 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);
// Assign your refresh layout
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Refreshable r = (Refreshable) adapter.getItemAt(pager.getCurrentItem());
r.refresh();
}
});
}
where each of your tab fragments implements a Refreshable interface:
public interface Refreshable {
void refresh();
}
and your adapter keeps track on all fragments:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// list that keeps references to all attached Fragments
private SparseArray<Fragment> pages = new SparseArray<>();
...
public Fragment getItem(int position) {
Fragment f;
if(position == 0) {
...
} else { ... }
// add fragment to the list
pages.put(position, f);
}
public void destroyItem(ViewGroup container, int position, Object object) {
// remove fragment from list if it existed
if(pages.indexOfKey(position) >= 0) {
pages.remove(position);
}
super.destroyItem(container, position, object);
}
// return the attached Fragment that is associated with the given position
public Fragment getItemAt(int position) {
return pages.get(position);
}
}