I am trying to display a fragment in a ViewPager and I would like to have a button to replace the fragment in the ViewPager. I have managed to set up using examplesIi found on stackoverflow. However, how can I toggle between the 2 fragmentA and FragmentB.
Thank you so much.
My code is as follows :
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final FragmentManager mFragmentManager;
private Fragment mFragmentAtPos0;
private Fragment mFragmentAtPos1;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager=fm;
}
#Override
public int getItemPosition(Object object)
{
if (object instanceof FragmentA && mFragmentAtPos0 instanceof FragmentB)
return POSITION_NONE;
if (object instanceof FragmentB && mFragmentAtPos1 instanceof FragmentA)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position){
case 1:
if (mFragmentAtPos1 == null)
{
mFragmentAtPos1 = FragmentB.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos1).commit();
mFragmentAtPos1 = new FragmentA();
notifyDataSetChanged();
showToast("in switchtoNextFragmentA ------------1");
}
});
}
return mFragmentAtPos1;
case 0:
if (mFragmentAtPos0 == null)
{
mFragmentAtPos0 = FragmentA.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();
mFragmentAtPos0 = new FragmentB();
notifyDataSetChanged();
showToast("in switchtoNextFragment");
}
});
}
return mFragmentAtPos0;
default: return null;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public class FragmentB extends Fragment {
Button button;
static FragmentB b;
static FirstPageFragmentListener fpl1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
return inflater.inflate(R.layout.frag_b, group, false);
}
public static Fragment newInstance(FirstPageFragmentListener firstPageFragmentListener) {
// TODO Auto-generated method stub
fpl1 = firstPageFragmentListener;
if (b == null)
b = new FragmentB();
return b;
}
public static FragmentB newInstance() {
if (b == null)
b = new FragmentB();
return b;
}
#Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fpl1.onSwitchToNextFragment();
}
});
}
}
UPDATE : layout file
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/lbltime"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:id="#+id/framelayout">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFCC" >
</android.support.v4.view.ViewPager>
</FrameLayout>
Its simple just do this
inside your button onClick method
Fragment f;
f = new FragmentTwo();
FragmentTransaction ft = getFragmentSupportManager().beginTransaction();
ft.replace(R.id.main_details_fragment_container, f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
Related
I am calling ViewPager(Fragment C) from a ListView(Fragment A). But this only works once. If I move back to my list and select another item , it doesnot move into the listview. It just shows a blank layout of fragment c.
Below is the code for Fragment A:
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
Communicator communicator;
ArrayList<Book> book_a;
ArrayList<String> book_titles;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
savedInstanceState = getArguments();
if (getArguments() != null) {
// savedInstanceState = getArguments();
book_a = (ArrayList<Book>) getArguments().getSerializable("bookarray");
book_titles = getList(book_a);
//Log.d("Frag_a:Title",book_a.get(5).getTitle());
list= (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,book_titles);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
return view;
}
public ArrayList<String> getList(ArrayList<Book> book2){
ArrayList<String> list_titles = new ArrayList<String>();
int size = book2.size();
for(int i=0;i<size;i++){
Book object;
object = book2.get(i);
list_titles.add(object.title);
}
return list_titles;
}
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
communicator.respond(position);
}
public interface Communicator{
public void respond(int index);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof Communicator){
communicator = (Communicator) context;
} else {
throw new RuntimeException(context.toString()+"must implement Communicator");
}
}
#Override
public void onDetach() {
super.onDetach();
communicator = null;
}
}
Below is the code for MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentA.Communicator{
FragmentB f2;
ArrayList<Book> b = new ArrayList<Book>();
FragmentManager manager;
static int flag = 0;
static String search="great";
SearchView sv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SearchView) findViewById(R.id.searchView);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
flag = 1;
search = query;
getBooks();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
getBooks();
return false;
}
});
getBooks();
/*
manager = getSupportFragmentManager();
f1 = (FragmentA) manager.findFragmentById(R.id.fragment);
f1.setCommunicator(this);*/
}
#Override
public void respond(int index) {
f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
if(f2!=null && f2.isVisible())
{
f2.changeData(index);
}
else
{
Bundle bundle = new Bundle();
bundle.putInt("index", index);
bundle.putSerializable("bookarray",(ArrayList<Book>)b);
Fragment newFragment = new FragmentC();
newFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
public void afterGetBooks(ArrayList<Book> bks) {
for (Book h : bks) {
b.add(h);
}
manager = getSupportFragmentManager();
Bundle args = new Bundle();
args.putSerializable("bookarray",(ArrayList<Book>)bks);
FragmentA f1 = new FragmentA();
f1.setArguments(args);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment,f1);
transaction.addToBackStack(null);
transaction.commit();
f1.setCommunicator(this);
}
private void getBooks(){
String url;
if(flag==0){
url = "https://kamorris.com/lab/audlib/booksearch.php/";}
else{
url = "https://kamorris.com/lab/audlib/booksearch.php?search=" + search;
flag=0;
}
//ArrayList<Book> boo;
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://kamorris.com/lab/audlib/booksearch.php/").addConverterFactory(GsonConverterFactory.create()).build();
Book.API api = retrofit.create(Book.API.class);
Call<ArrayList<Book>> call = api.getBooks(url);
call.enqueue(new Callback<ArrayList<Book>>() {
#Override
public void onResponse(Call<ArrayList<Book>> call, Response<ArrayList<Book>> response) {
ArrayList<Book> Books = response.body();
for(Book h: Books){
Log.d("Retro-Title",h.getTitle());
//b.add(h);
}
afterGetBooks(Books);
}
#Override
public void onFailure(Call<ArrayList<Book>> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
Below is the code for Fragment C:
public class FragmentC extends Fragment {
ViewPager vp;
static int list_pos;
FragmentPagerAdapter adapterViewPager;
public static ArrayList<Book> book_c;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_c,container,false);
if(getArguments()!= null){
book_c = (ArrayList<Book>) getArguments().getSerializable("bookarray");
list_pos = getArguments().getInt("index");
}
vp = (ViewPager) view.findViewById(R.id.viewpager);
adapterViewPager = new MyPagerAdapter(getFragmentManager());
vp.setAdapter(adapterViewPager);
return view;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 11;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (list_pos) {
case 0: // Fragment # 0 - This will show FirstFragment
list_pos = position;
return FragmentB.newInstance(book_c,0);
case 1: // Fragment # 0 - This will show FirstFragment different title
list_pos = position;
return FragmentB.newInstance(book_c,1);
case 2: // Fragment # 1 - This will show SecondFragment
list_pos = position;
return FragmentB.newInstance(book_c,2);
case 3: list_pos = position;
return FragmentB.newInstance(book_c,3);
case 4:list_pos = position;
return FragmentB.newInstance(book_c,4);
case 5:list_pos = position;
return FragmentB.newInstance(book_c,5);
case 6:list_pos = position;
return FragmentB.newInstance(book_c,6);
case 7:list_pos = position;
return FragmentB.newInstance(book_c,7);
case 8:list_pos = position;
return FragmentB.newInstance(book_c,8);
case 9:list_pos = position;
return FragmentB.newInstance(book_c,9);
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
}
Also is there a way, where I can start my viewpager from the description of the listitem which I selected.
Also Fragment B is just a text view holder.
I tried to see the control flow with the debugger. But when I try it that way these lines in Fragment C are not working ..
{
book_c = (ArrayList<Book>) getArguments().getSerializable("bookarray");
list_pos = getArguments().getInt("index");
}
vp = (ViewPager) view.findViewById(R.id.viewpager);
adapterViewPager = new MyPagerAdapter(getFragmentManager());
vp.setAdapter(adapterViewPager);
Your fragment has not been destroyed and therefore when it is brought back, onCreateView is not being called. Instead override setUserVisibleHint.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// This is true when your fragment is visible, write code to populate view here
} else {
// This is true when your fragment is hidden.
}
}
The solution i found is to change the Fragment Manager
adapterViewPager = new MyPagerAdapter(getFragmentManager());
to
adapterViewPager = new MyPagerAdapter(getChildFragmentManager());
I Have 4 Fragments in 1 Activity. I need to make sure that on every fragment change the fragment is refreshed because I load JSON Data in every fragment. I use FragmentPager Adapter and RecyclerView to Show Data
This is my Adapter ( SickAdapter.java ) the code :
public class SickAdapter extends FragmentPagerAdapter{
private static final String TAG = SickAdapter.class.getSimpleName();
private static final int FRAGMENT_COUNT = 4;
public SickAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new SickFragmentToAll();
case 1:
return new SickFragmentToPending();
case 2:
return new SickFragmentToApproved();
case 3:
return new SickFragmentToDenied();
}
return null;
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "All";
case 1:
return "Pending";
case 2:
return "Approved";
case 3:
return "Denied";
}
return null;
}
}
In my Class ( SickClass.java ) I create SickClass and I Call SickAdapter, I explode them, and this is my Code :
public class SickClass extends Fragment {
private static final String TAG = SickClass.class.getSimpleName();
private SickAdapter mAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
public SickClass() {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.employee_leave_class, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
viewPager = (ViewPager)view.findViewById(R.id.view_pager);
if(mAdapter == null) {
mAdapter = new SickAdapter(getChildFragmentManager());
}
viewPager.setAdapter(new SickAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1, true);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
Try below code for reload your fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(YOUR_FRAGMENT_NAME.this).attach(YOUR_FRAGMENT_NAME.this).commit();
You can use startActivityForResult() to get the result from the activity.
References:
ViewPager PagerAdapter not updating the View
How to refresh a Fragment of a FragmentPagerAdapter?
I have tabbed activity and I want to have youtube video on third tab.
here's my java :
public class FragmentTutorial extends YouTubePlayerFragment {
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
public FragmentTutorial() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
youTubePlayerView = (YouTubePlayerView) youTubePlayerView.findViewById(R.id.tutorial_youtube_player);
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("3LiubyYpEUk");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
youTubePlayerView.initialize(PlayerConfig.API_KEY, onInitializedListener);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tutorial, container, false);
}
}
and here's my XML :
<FrameLayout 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="com.example.FragmentTutorial">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tutorial_youtube_player" />
</FrameLayout>
and here's my MainActivity :
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentHome();
case 1:
return new FragmentCatalog();
case 2:
return new FragmentTutorial();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0: return "Home";
case 1: return "Catalog";
case 2: return "Tutorial";
default: return null;
}
}
}
when I tried to run this code, I got this following error :
Error:(80, 28) error: incompatible types: FragmentTutorial cannot be converted to Fragment
what did I missed here? thank you...
Probably it is caused by the wrong Fragment class, YouTubePlayerFragment extends android.app.Fragment, FragmentPagerAdapter requires android.support.v4.app.Fragment and this cannot be converted
Edit:
try to use android.support.v13.app.FragmentPagerAdapter instead android.support.v4.app.FragmentPagerAdapter (other fragments should extends android.app.Fragment)
I know this is very general question but can't able to figure out what is wrong.
Fragment java class
// newInstance constructor for creating fragment with arguments
public static BpDetails newInstance(int page) {
BpDetails fragmentFirst = new BpDetails();
Bundle args = new Bundle();
args.putInt("someInt", page);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
}
public String getSystolic(){
return this.systolic.getText().toString();
}
/* public String getDiastolic(){
return this.diastolic.getText().toString();
}*/
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.bp_details, container, false);
Log.i("View ",view.toString());
Log.i("DOB is ",Long.toString(Constants.dob));
systolic =(EditText) view.findViewById(R.id.systolic);
diastolic =(EditText) view.findViewById(R.id.diastolic);
return view;
}
ViewPager Activity
vpPager = (ViewPager) findViewById(R.id.view_pager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
findViewById(R.id.btn_prev).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(-1);
if (current!=0)
prevPage=current-1;
if (current < 4) {
// move to next screen
vpPager.setCurrentItem(current);
} else {
//final reached.
}
}
});
findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current!=0)
prevPage=current-1;
System.out.println("Prev page "+prevPage);
if (current < 4) {
// move to next screen
Fragment bpFragment=adapterViewPager.getItem(vpPager.getCurrentItem());
if (bpFragment instanceof BpDetails){
System.out.println("Current item is "+vpPager.getCurrentItem());
BpDetails fr = (BpDetails)adapterViewPager.getItem(vpPager.getCurrentItem());
**String systolicString = fr.getSystolic();** //error point
Log.i("Systolic is ",systolicString);
}
} else {
//final reached.
}
}
});
}
private int getItem(int i) {
return vpPager.getCurrentItem() + i;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static int mSelectedPosition;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
//mSelectedPosition=selectedPosition;
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return BasicDetails.newInstance(0);
case 1:
return BpDetails.newInstance(1);
case 2:
return BslDetails.newInstance(2);
case 3:
return Summary.newInstance(3);
default:
return null;
}
}
}
Why I am getting the nullpointerException since I am accessing the public method of fragment before going to the next fragment.
Before down voting please leave the reason of down voting so that I can improve the question.
EDit:
I got to know since I am calling the getitem() method thats why all the variable of fragment to null that why I am getting the nullpointerException. Is there any way I solve this problem.
you should rewrite your ViewPagerAdapter and store the retuened fragment
this is because every time you call getItem() function you return a new fragment,but only invoked by the viewpager itself the fragment will invoke oncreateView ,so the second time you call getItem did not initialize the systolic and thus lead to NUllPointerException
for reference:
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static int mSelectedPosition;
Map<Integer,Fragment> map= new HashMap<>();
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
//mSelectedPosition=selectedPosition;
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
Fragment f = map.get(position)
if(f!=null){
return f;
}
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
f = BasicDetails.newInstance(0);
case 1:
f = return BpDetails.newInstance(1);
case 2:
f = return BslDetails.newInstance(2);
case 3:
f = return Summary.newInstance(3);
default:
return null;
}
map.put(postion,f);
return f;
}
}
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.