Run new fragment instance with viewpager on click on menu item - java

I have a working fragment code based on Android Studio's "Tabbed Activity" project structure. However, since I have dynamically created content filling the space, the standard swipe isn't applicable and I'd like to toggle between fragments when selecting an item from a menu.
This is my code for the fragments:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
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 containerPager,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, containerPager, false);
TextView textView = (TextView) rootView.findViewById(R.id.temporary);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
// FRAGMENT 1 - First. This one should have a blank layout!
public static class FragmentFirst extends Fragment {
public static FragmentFirst newInstance(int sectionNumber) {
FragmentFirst fragment = new FragmentFirst();
return fragment;
}
public FragmentFirst() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, containerPager, false);
return rootView;
}
}
// FRAGMENT 2 - Second
public static class FragmentSecond extends Fragment {
public static FragmentSecond newInstance(int sectionNumber) {
FragmentSecond fragment = new FragmentSecond();
return fragment;
}
public FragmentSecond() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, containerPager, false);
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).
switch (position) {
case 0:
return FragmentFirst.newInstance(position + 1);
case 1:
return FragmentSecond.newInstance(position + 1);
default:
//assume you only have 2
throw new IllegalArgumentException();
}
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
OnCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.containerPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
Furthermore, here is the code for choosing the particular menu item:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.change_fragment)
{
// Can I run/initiate the code at public Fragment getItem(int position) {}
// from here?
// The lines below do work, but rather than running the fragments' code,
// it simply overlaps with the current content.
ViewPager mViewPager = (ViewPager) findViewById(R.id.containerPager);
mViewPager.setCurrentItem(1, true);
return true;
}
return super.onOptionsItemSelected(item);
}
I am familiar with mViewPager.setCurrentItem(position, true), however, rather than applying the fragment over the current layout, I'd like to trigger the fragment code so it can change between layouts - in this case, to fragment_main, or FragmentSecond.
Problem:
Is it possible to run the code in public Fragment getItem(int position) {} outside its class SectionsPagerAdapter extends FragmentPagerAdapter? Or is there a better way to achieve what I'm looking for?

public Fragment getItem(int position) {
switch(position)
{
case 0:
FragmentMain tab1 = new FragmentMain ();
return tab1;
case 1:
FragmentSecond tab2 = new FragmentSecond ();
return tab2;
default:
return null;
}
i use this to switch fragments

XML :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabIndicatorColor="#color/black"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/black"
app:tabTextAppearance="#style/buttonThemePrimaryHolo1"
app:tabTextColor="#fff" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
In Activity :
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
viewPager = findViewById ( R.id.viewpager );
setupViewPager ( viewPager );
tabLayout = findViewById ( R.id.tabs );
tabLayout.setupWithViewPager ( viewPager );
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter ( getSupportFragmentManager () );
adapter.addFragment ( new Fragment1 (), "Fragment1 " );
adapter.addFragment ( new Fragment2 (), "Fragment2 " );
adapter.addFragment ( new Fragment3 (), "Fragment3 " );
adapter.addFragment ( new Fragment4 (), "Fragment4 " );
viewPager.setAdapter ( adapter );
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List <Fragment> mFragmentList = new ArrayList <> ();
private final List <String> mFragmentTitleList = new ArrayList <> ();
public ViewPagerAdapter(FragmentManager manager) {
super ( manager );
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get ( position );
}
#Override
public int getCount() {
return mFragmentList.size ();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add ( fragment );
mFragmentTitleList.add ( title );
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get ( position );
}
}
In Fragment
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter ( getChildFragmentManager() );
adapter.addFragment ( new Fragment1 (), "Fragment1 " );
adapter.addFragment ( new Fragment2 (), "Fragment2 " );
adapter.addFragment ( new Fragment3 (), "Fragment3 " );
adapter.addFragment ( new Fragment4 (), "Fragment4 " );
viewPager.setAdapter ( adapter );
}
Other part are same as activity in fragment

Related

RecyclerView: No adapter attached; skipping layout - What is missing in the main?

Before put -1 in the score, I tell you that I read all, I repeat ALL the answers about this problem in this site and even in other site, so, if you can give me an hand.
Hi guys, i'm having this problem with my application and I'm wasting too much time in this.
My application is composed by 4 fragments, and I'm having problems with the two with the recyclerview (in fragment_fibra and fragment_adsl).
main.java
public class main extends AppCompatActivity implements
OnFragmentInteractionListener //I HAVE a problem with
OnFragmentInteractionListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(mViewPager); //aggiunta dopo
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(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_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) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(1);
case 1:
return PlaceholderFragment.newInstance(2);
case 2:
return PlaceholderFragment.newInstance(3);
case 3:
return PlaceholderFragment.newInstance(4);
default: return PlaceholderFragment.newInstance(1);
// here i have other problems, so like this the app still work, but if i change something it crash (and I know it's wrong like this)
}
//return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
activity_homepage.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".homepage">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
homepage.java (first fragment)
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 = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = 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() {
return 4;
}
}
}
fragment_fibra.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fibra"
android:background="#EFEFEF">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:drawablePadding="22dp"
android:gravity="center"
android:hint="#string/cercasugg"
android:textColor="#000000"
android:padding="16dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/ListaFibra"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fibra.java (second fragment)
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
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);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_fibra, container, false);
recyclerView = V.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
List<String> input = new ArrayList<>();
for (int i = 0; i < 100; i++) {
input.add("Test" + i);
}
mAdapter = new adFibra(input);
recyclerView.setAdapter(mAdapter);
return V;
/*View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true); //per migliorare performance
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
adFibra adapter = new adFibra(new String[]{"Example One"});
recyclerView.setAdapter(adapter);
return rootView;*/
//return inflater.inflate(R.layout.fragment_fibra, container, false);
}
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 {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
try to put
recyclerView.setLayoutManager(llm);
before
recyclerView.setAdapter(adapter);
so it will be
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
MyAdapter adapter = new MyAdapter(new String[]{"Example One", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
recyclerView.setAdapter(adapter);
Happy Coding :D
Are you sure you actually call the fibra fragment?
You are creating a PlaceHolderFragment every time and just inflating different layouts. You don't actually create a fibra fragment, so the recycler is not populated, thus the message.
In your SectionsPagerAdapter, in method getItem, return the fragment instance that corresponds to the position.
For example:
switch (position) {
case 0:
return homepage.newInstance();
case 1:
return fibra.newInstance();
case 2:
return adsl.newInstance();
case 3:
return aiuto.newInstance();
default:
return homepage.newInstance();
}
Remove the PlaceHolderFragment from your main activity. Also homepage is not a fragment, but an activity. All your fragments should look like fibra.
And implement all the fragment interfaces like:
implements fibra.OnFragmentInteractionListener
and create a method to implement it:
#Override
public void onFragmentInteraction(Uri uri) {
// your code here...
}

How do I use android fragment java class?

I set up a fragment which looks like this:
The EditText("5") has the id et_input. Now I want to interact with my EditText but it doesn't work.
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
getSupportActionBar().hide();
}
/**
* 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() {
}
/**
* 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) {
switch (getArguments().getInt(ARG_SECTION_NUMBER) - 1) {
case 1:
return inflater.inflate(R.layout.fragment_roman_numbers, container, false);
case 2:
return inflater.inflate(R.layout.fragment_binary_numbers, container, false);
default:
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return main.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
return null;
}
}
}
binary_numbers.java
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
roman_numbers.java and main.java look exactly the same except for binary_numbers being replaced with their names.
fragement_binary_numbers.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ngtnttnmnt.xtool.MainActivity$PlaceholderFragment">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/et_input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:hint="#string/input_hint"
android:gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_output"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="40dp"
android:gravity="center" />
fragement_roman_numbers.xml looks exactly the same and fragement_main.xml has two TextView's
Should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
EDIT:
As I said, you're showing a different fragment. In reality, you are showing the PlaceholderFragment created within your SectionsPagerAdapter, which just selects the binary_number layout when it's inflated, but you're not actually showing a binary_numbers fragment.
Your code should be the following:
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);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
getSupportActionBar().hide();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return home.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
}
}
Please note the complete removal of the PlaceholderFragment class, because you won't need it, ever.
EDIT: also add
public class home extends Fragment {
public static home newInstance() {
return new home();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
EDIT:
Also modify your binary_numbers class like so
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.ngtnttnmnt.xtool.InputFilterMinMax;
import com.ngtnttnmnt.xtool.R;
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private PlaceholderFragment mPlaceholderFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(mPlaceholderFragment == null){
mPlaceholderFragment = PlaceholderFragment.newInstance(position + 1);
}
return mPlaceholderFragment;
}
It should be like this

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;
}
}

Android Swipe View help needed

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.

Android SwipeViews + TitleStrip + ListView

My new project consists of a Navigation Drawer with 6 fragments ( Audi / BMW / KIA... car brads ). I want each Fragment to have 2 other fragments ( Models, which will have a ListView with car models and the second fragment, called Pictures, it's obvious what that contains). I don't like tabs, that's why I chose TitleStrip with swipe navigation between the fragments.
BMW.java
public class BMW extends Fragment {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(com.zenyt.R.layout.fragment_bmw, container, false);
mCollectionPagerAdapter = new CollectionPagerAdapter(
getFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActivity().getActionBar();
// Specify that the Home button should show an "Up" caret, indicating
// that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) rootView.findViewById(R.id.bmw_pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
return rootView;
}
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
final int NUM_ITEMS = 2; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
}
return tabLabel;
}
}
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
private ListView myListView;
private String[] strListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.models;
break;
case 1:
tabLayout = R.layout.pictures;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
}
In TabFragment, I want fragments instead of layouts (models and pictures). How can I do that?
models.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#android:color/black"
>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2" />
</RelativeLayout>
Models.java
public class Models extends Fragment {
private ListView myListView;
private String[] strListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(com.zenyt.R.layout.models, container, false);
myListView = (ListView) rootView.findViewById(com.zenyt.R.id.listView2);
strListView = getResources().getStringArray(com.zenyt.R.array.bmw_list_data);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, strListView);
myListView.setAdapter(objAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
return rootView;
}
}
Seems that I solved it by myself. All I had to do was to change a bit the PagerAdapter, like this:
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new Bmw1();
case 1:
return new Bmw2();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
}
return tabLabel;
}
}

Categories