Android Swipe View help needed - java

I have a swipe Activity, with 2 swipe pages, I added the content for the first page and on the second page the content is duplicated, how can I set different content to the second page in my swipe view?
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
return rootView;
}
}
}

Android Developers site really has very good explanation of ViewPager. You should check it out:
http://developer.android.com/training/animation/screen-slide.html
Here is an example I wrote:
activity_screen_slide.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java Code:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...
public class ScreenSlidePagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
//Create these fragments with your preferable names
switch (position) {
case 0:
return new ScreenSlidePageFragment();
case 1:
return new ScreenSlidePageFragment2();
default:
break;
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
And here is one of your views that should look like it where fragment_ screen_slide_page is one of your layouts:
import android.support.v4.app.Fragment;
...
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
You should really read the android developers site for further details.

You can return different fragments like this:
#Override
public Fragment getItem(int position) {
if (position == 0) {
return PlaceholderFragment.newInstance(position + 1);
} else {
return anotherFragment.newInstance();
}
}
If you want to use the same Fragment, you can change the content depending on the position you are passing to the fragment.

Related

RecyclerView: No adapter attached; skipping layout? What should I do? [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 4 years ago.
Today I'm having this issue with my application; I want to say that I read almost ALL the other questions here on StackOverflow but nothing, always the same problem.
homepage.java (main class)
public class homepage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
}
MyAdapter.java (default code from Android Studio Guide)
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public MyViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TextView v = (TextView) LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
And finally, one of the fragment that I'm using:
fibra.java
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private MyAdapter adapter;
private LinearLayoutManager llm;
String [] prova={"prova1","prova2","prova2","prova2","prova2","prova2","prova2"};
public fibra() {
}
public static fibra newInstance(String param1, String param2) {
fibra fragment = new fibra();
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);
//setContentView(R.layout.my_activity); (doesn't work "cannot resolve method")
recyclerView.setHasFixedSize(true); //per migliorare performance
llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
adapter = new MyAdapter(prova);
recyclerView.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
return rootView;
}
// 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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Here:
//setContentView(R.layout.my_activity); (doesn't work "cannot resolve method")
It's like inflating a layout inside an Activity which you already have onCreateView and in a Fragment.
Change the first codes to :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
Then, initialize RecyclerView inside onCreateView().
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
// Here you should initialize RecyclerView and other widgets by rootView.findViewById and etc
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true); //per migliorare performance
llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
adapter = new MyAdapter(prova);
recyclerView.setAdapter(adapter);
return rootView;
}
You forget to add tablaylout.setupWithViewPager(mViewPager); in your homepage.java

OnClick Fragment to Fragment switch results in Blank Screen

When switching from one fragment to another fragment (within the second tab of my application), my second fragment is blank. I have tried the solutions linked here, but none seem to work:
Transaction of fragments in android results in blank screen
Android: Getting white screen with fragment transaction
MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter, and add pages.
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter.addPage(new Received());
mSectionsPagerAdapter.addPage(new Send());
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_alert_partners, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_received, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_send, container, false);
return rootView;
}
else {//main empty fragment in case of error. Never used in normal behaviour.
View rootView = inflater.inflate(R.layout.fragment_alert_partners, container, false);
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//Create an Array list that will hold the pages.
ArrayList<Fragment> pages = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return pages.get(position);
}
//Add a page
public void addPage(Fragment f) {
pages.add(f);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Send";
}
return null;
}
}
}
SendFragment:
public class Send extends Fragment {
private OnFragmentInteractionListener mListener;
private TextView text1;
public Send() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_send, container, false);
//Need getView() for fragment since setContentView must be set first but is not possible in fragment.
text1 = (TextView)v.findViewById(R.id.textview1);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Send2 send2 = new Send2();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.hide(Send.this);
fragmentTransaction.add(android.R.id.content, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
public interface OnFragmentInteractionListener {
}
}
Send2Fragment:
public class Send2 extends Fragment {
private OnFragmentInteractionListener mListener;
public Send2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_send2, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
}
}
Had to add a framelayout at the end of the layout code for the fragment I was replacing:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/send1frameLayoutId">
</FrameLayout>
Then used this code to switch to a fragment in the same tab of the previous fragment:
Fragment send2 = new Send2();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.send1frameLayoutId, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Putting viewpager in a dialog error "getSupportFragmentManager()"

I'm trying to put a viewpager in a custom dialog (wasabeef's blurdialogfragment) but, I don't whats the problems, or how to replace it, because it's says: "cannot resolve method getSupportFragmentManager()"
If anyone can help me with this, i would be thankful..
Code:
public class DialogHelperForNoobs extends BlurDialogFragment {
String personName;
String personGivenName;
String personFamilyName;
String personEmail;
String personId;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public DialogHelperForNoobs() {
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createDialogHelperForNoobs();
}
public AlertDialog createDialogHelperForNoobs() {
Bundle mArgs = getArguments();
//Datos Usuario
personName = mArgs.getString("personName");
personGivenName = mArgs.getString("personGivenName");
personFamilyName = mArgs.getString("personFamilyName");
personEmail = mArgs.getString("personEmail");
personId = mArgs.getString("personId");
//INFLADOR DIALOGO
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.activity_dialog_helper_for_noobs, null);
//Error in FragmentManager getSupportFragmentManager()
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) v.findViewById(R.id.ViewPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
builder.setView(v);
return builder.create();
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_pager_noobs, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
Anyone can help? Thanks.
Depends where you are calling it from but I suspect it is because you are calling this from the fragment when getSupportFragmentManager is a method on the AppCompatActivity class

How To Hide View on Specific Fragment

I want to hide a GridView by setting drawerGrid.setVisibility(View.GONE); when the ViewPager is on a specific layout. Do I need to implement a onPageListener or is there an easier option?
Launcher.java
public class Launcher extends FragmentActivity {
DrawerAdapter drawerAdapterObject;
GridView drawerGrid;
class Package {
Drawable icon;
String name;
String label;
}
Package[] packs;
PackageManager pm;
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
pm=getPackageManager();
set_packs();
drawerAdapterObject = new DrawerAdapter(this, packs);
drawerGrid.setAdapter(drawerAdapterObject);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void set_packs() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packsList = pm.queryIntentActivities(mainIntent, 0);
packs = new Package[packsList.size()];
for(int I=0;I<packsList.size();I++){
packs[I]= new Package();
packs[I].icon=packsList.get(I).loadIcon(pm);
packs[I].name=packsList.get(I).activityInfo.packageName;
packs[I].label=packsList.get(I).loadLabel(pm).toString();
}
}
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_apps,container,false);
}
}
Fragment2.java
public class Fragment2 extends Fragment {
ViewPager viewpager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_homescreen,container,false);
}
}
You can do that in two ways:
As you mentioned by using addOnPageChangedListener
Using callback when your fragment become visible to user
How to determine when Fragment becomes visible in ViewPager:
try this;
public class MyFragment extends Fragment {
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//hide view here
}
else {
}
}
}
setUserVisibleHint
Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.
here isVisibleToUser boolean: returns true if this fragment's UI is currently visible to the user (default), false if it is not.

Android: ViewPager displays only first fragment, other pages blank

I have a ViewPager that displays a series of FoodItem as Fragments. That part works just fine.
Now, I want to have a function such that if a user clicks on a button, they can view more information about that FoodItem.
For that, I want to replace the clicked Fragment with another Fragment. I modified this code here to suit my purpose. It works -- when I click the button, it replaces that certain Fragment. But it only displays and works for one Fragment. Other fragments are blank entirely.
Here's my adapter and fragments:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<FoodItem> items;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<FoodItem> items) {
super(fm);
this.items = items;
}
#Override
public Fragment getItem(int position) {
System.out.println("PRINT: POS " + position);
RootFragment f = new RootFragment();
return f.newInstance(position);
}
#Override
public int getCount() {
return items.size();
}
public class PlaceholderFragment extends Fragment{
private final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
System.out.println("PRINT: INSTANCE" + sectionNumber);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_card_layout, container, false);
singleItem = items.get(getArguments().getInt(ARG_SECTION_NUMBER));
// populate views here
//Below is the button for replacing the Fragment with another Fragment.
Button testMore = (Button) view.findViewById(R.id.testMore);
testMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
trans.replace(R.id.root_frame, new MoreInfoFragment().newInstance(getArguments().
getInt(ARG_SECTION_NUMBER)));
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
return view;
}
}
public class MoreInfoFragment extends Fragment {
private final String ARG_SECTION_NUMBER = "section_number";
public MoreInfoFragment newInstance(int sectionNumber) {
MoreInfoFragment fragment = new MoreInfoFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public MoreInfoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.more_info_layout, container, false);
singleItem = items.get(getArguments().getInt(ARG_SECTION_NUMBER));
//populate views here
return view;
}
}
public class RootFragment extends Fragment {
private static final String TAG = "RootFragment";
private final String ARG_SECTION_NUMBER = "section_number";
public RootFragment newInstance(int sectionNumber) {
RootFragment fragment = new RootFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.root_frame, new PlaceholderFragment().newInstance(getArguments().
getInt(ARG_SECTION_NUMBER)));
System.out.println("PRINT: ROOT" + getArguments().getInt(ARG_SECTION_NUMBER));
transaction.commit();
return view;
}
}
}
Here's my Main Activity:
private ViewPager mViewPager;
private static ArrayList<FoodItem> sample;
private PagerContainer mContainer;
public CardLayout(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.activity_card_layout);
//Sample array
sample = new ArrayList<>();
sample.add(new FoodItem("French Fries", "Super delicious and crispy!"))
sample.add(new FoodItem("Burger", "Made with real Krabby Patty"))
sample.add(new FoodItem("Pickles", "So green")) // This is the only one that displays
//PagerContainer is a FrameLayout that has a ViewPager as a child.
//I want my ViewPager to display edges of the previous and next part so
//PagerContainer is used for that purpose.
mContainer = (PagerContainer) findViewById(R.id.pager_container);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
// This is to adjust the viewpager according to size of screen
mContainer.getViewTreeObserver().
addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
height = mContainer.getHeight();
double heightSize = height * 0.8;
height = (int) heightSize;
double widthSize = height*0.6;
width = (int) widthSize;
mViewPager.setLayoutParams(new FrameLayout.LayoutParams(width, height, Gravity.CENTER));
mViewPager.setPageMargin(width /30);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
mContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
else
mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), sample);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(mSectionsPagerAdapter.getCount());
mViewPager.setClipChildren(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
Oh, the Fragment that's displaying is not even the first one in my ArrayList! It's the last.
I feel like I'm missing something obvious but I've looked through this code about 10 times and I still couldn't find what could have prevented the other pages from displaying.
For example, this is how the first page looks like:
If I slide to the second page, it's totally white (my background color for root_fragment)
And that goes for every fragments after.
Do you guys have any ideas/suggestions?
Override the method getItem() in your SelectionsPageAdapter
#Override
public Fragment getItem(int position) {
// if the position is 0 we are returning the First tab
if (position == 0)
{
Fragment tab1 = new PlaceholderFragment ();
return tab1;
} else if (position == 1)
{
Fragment tab2 = new MoreInfoFragment ();
return tab2;
} else if (position == 2) {
Fragment tab3 = new RootFragment ();
return tab3;
}
}

Categories