Replacement fragments in in pagerView - android

`Facing one problem in android that I created a pager View and two fragments lets say fragment A and fragment B are attached...
My question is: There is a button in fragment A after clicking on that button I want to load fragment C which will be the replacement of fragment A in the same pager view how can it be done? But when I try below code content of Fragment C is shown over the fragment A ... can u help me with this please. I searched everywhere but didn't get the proper solution.
here is my code...
public class MainActivity extends AppCompatActivity implements Top_Fragment.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar=findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.pagerView);
viewPager.setAdapter(myPagerAdapter);
TabLayout tabLayout=findViewById(R.id.tab_bar);
tabLayout.setupWithViewPager(viewPager);
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Top_Fragment();
case 1:
return new FavoriteFrag();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.Items);
case 1:
return getResources().getString(R.string.favoriteItems);
}
return null;
}
}
#Override
public void onFragmentInteraction(int position) {
Fragment fragment=null;
switch (position){
case 0:
fragment=new DrikCategaryFrag();
}
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frameContainer,fragment);
ft.commit();
}
}
Main activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/frameContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pagerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>
</FrameLayout>
</LinearLayout>

Try this:
Viewpager with multiple fragments:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
default: return FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
activity_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
FirstFragment.java
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}

Related

Replace fragment in fragment itself in TabActivity

I am sorry on the duplicate question but I didn't get answer for my problem.
I create app with TabActivity and also trying to replace one fragment from fragment itself, I read in https://developer.android.com/training/basics/fragments/fragment-ui.html how to do it and i created interface in my fragment that i want to be replace with another,
I implement the interface in my MainActivity and still when running my app it show me container itself.
here is my code:
Main Activity:
public class MainActivity extends FragmentActivity implements New2.OnReplaceFragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static MainActivity instance = null;
public static MainActivity getInstance(){
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
instance = this;
}
#Override
public void onReplaceFragment(Class fragmentClass) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container,fragment);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
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) {
View rootView = inflater.inflate(R.layout.fragment_main, 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).
switch (position) {
case 0:
// New1 tab1 = new New1();
return New1.newInstance();
case 1:
return New2.newInstance();
case 2:
return New3.newInstance();
default:
return null;
}
}
#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;
}
}
}
my fragment that I want to replace
Fragment:
public class New2 extends Fragment {
TextView name;
Button change;
ImageView image1;
Animation anime;
private OnReplaceFragment dataPasser;
public static New2 newInstance(){
New2 fragment = new New2();
return fragment;
}
public New2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (TextView) rootView.findViewById(R.id.nameTt);
change = (Button) rootView.findViewById(R.id.changeBtn);
image1 = (ImageView) rootView.findViewById(R.id.image1);
anime = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.zoom);
change.setOnClickListener(changeName);
return rootView;
}
View.OnClickListener changeName = new View.OnClickListener() {
#Override
public void onClick(View view) {
image1.startAnimation(anime);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run(){
dataPasser.onReplaceFragment(Result.class);
}
},1000);
}
};
public interface OnReplaceFragment {
public void onReplaceFragment(Class fragmentClass);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
dataPasser = (OnReplaceFragment) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onDataPass");
}
}
}
the fragment that i want to display
public class Result extends Fragment {
TextView textView;
Button btnBack;
public static Result instance = null;
public static Result getInstance(){
return instance;
}
public Result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_result, container, false);
textView = (TextView) v.findViewById(R.id.text11);
btnBack = (Button) v.findViewById(R.id.btnBack);
textView.setText("working!!");
Toast.makeText(getActivity().getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return v;
}
}
Main Activity 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="com.example.hercules.tadhosttutrial.MainActivity">
<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:background="#color/red"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
New2 XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/changeBtn"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="change"/>
<ImageView
android:id="#+id/image1"
android:background="#drawable/icon_complete"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
Result 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:background="#color/colorAccent"
tools:context="com.example.hercules.tadhosttutrial.Result">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"/>
<TextView
android:id="#+id/text11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WORKING"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="70dp"
/>
</RelativeLayout>
What i mean, is making MainActivity as a main container for all fragments, either with tabs or just a regular fragment,
1- Main Activity XML: remove ViewPager, add a FrameLayout instead (use same id)
2- Create new fragment TabsFragment with this XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
3- Move initializing SectionsPagerAdapter and ViewPager from main activity to TabsFragment:
this part:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
and this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
4- I think moving SectionsPagerAdapter class in a new file is better too.
now if you want default view for app to be the tabs, then in MainActivity at onCreate() show TabsFragment by calling your method:
onReplaceFragment(TabsFragment.class);
now every thing should work fine, because the idea here is to replace the fragment displayed in main activity with another one
in this case TabsFragment, Result, and New2
not to replace viewpager fragments (because as i told you this is managed via the adapter) not by calling replace()
you may need to play around this, it's not a final code, just something to give you idea about it.

Can a fragment be a host to a view pager instead of an activity?

Can a view pager be put in a fragment's layout, so this fragment would be the host to a few other fragments? So far I've seen only Activities as a host.
Yes, you can, use the code bellow
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
}
view the full implementation here https://github.com/marcoRS/nested-fragments/tree/master/src/com/burnside/digital/nestedfragments
Yes, it is possible.
Here is an example (Use TabHost inside a Fragment with a ViewPager):
public class GroupFragment extends Fragment {
private static TabLayout tabLayout;
private static ViewPager viewPager;
private static final int int_items = 4 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position){
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
case 2 : return new UpdatesFragment();
case 3 : return new TeamFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Grupo A";
case 1 :
return "Grupo B";
case 2 :
return "Grupo C";
case 3:
return "Grupo D";
}
return null;
}
}
}
And the Layout of the fragment is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
I hope that helps.

Android: TabLayout not showing any tabs

First time working with com.android.support:design:23.1.1, and having some issues getting TabLayout to work.
My app is basically set up as such:
One main activity called LandingActivity which has a DrawerLayout with menu items in it.
When selecting a menu item, I load different Fragments into a FrameLayout in the LandingActivity.
Some of the loaded Fragments should show tabs at the top, some shouldn't.
My issue is, on the Fragment which is supposed to show tabs at the top, it has extra space in the nav bar like it should have tabs there, but nothing shows.
Code:
activity_landing.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer" />
LandingActivity where I load the fragments:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
switch(menuItem.getItemId()) {
case R.id.drawer_home:
fragment = HomeFragment.newInstance();
break;
case R.id.drawer_customize:
fragment = CustomizeFragment.newInstance();
break;
default:
fragment = HomeFragment.newInstance();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
home_fragment.xml (one which has tabs)
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
HomeFragment.java
public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
Bundle args = new Bundle(); alreadySelectedFollowingInfo);
HomeFragment fragment = new HomeFragment();
fragment.setArguments(args);
return fragment;
}
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_home, container, false);
final TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("One"));
tabLayout.addTab(tabLayout.newTab().setText("Two"));
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter
(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return inflater.inflate(R.layout.fragment_home, container, false);
}
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
BlogFragment tab1 = BlogFragment.newInstance();
return tab1;
case 1:
TrendingFragment tab2 = TrendingFragment.newInstance();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
Might not be relevant, but tool_bar.xml used in activity_landing.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="?attr/colorPrimary">
That's about all I've got. Can't figure out what's going on.
EDIT:
New code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
return v;
}
private void setupViewPager(ViewPager viewPager) {
PagerAdapter adapter = new PagerAdapter(getFragmentManager());
adapter.addFragment(BlogFragment.newInstance(), "ONE");
adapter.addFragment(TrendingFragment.newInstance(), "TWO");
viewPager.setAdapter(adapter);
}
class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(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);
}
}
return inflater.inflate(R.layout.fragment_home, container, false);
in your onCreateView means that you return a newly inflated home fragment without any of your initialization code.
You should be returning the view that you created at the beginning of onCreateView:
return v;
Sample PagerAdapter that provides tab titles:
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
And so, your refactored onCreateView code would be something like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
final TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
PagerAdapter adapter = new PagerAdapter(getFragmentManager());
adapter.addFragment(BlogFragment.newInstance(), "One");
adapter.addFragment(TrendingFragment.newInstance(), "Two");
viewPager.setAdapter(adapter);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return v;
}
Return your initialized infleted view while you are returning
return inflater.inflate(R.layout.fragment_home, container, false);
while you should return view v from first line of onCreateView
final View v = inflater.inflate(R.layout.fragment_home, container, false);

move from a fragment to another in an activity

From what I understand from this thread, fragments can be easily replaced with another.
However in my case, I have 2 fragments combined in scrollable Activity, so when I say "move", I mean going from the fragment left to the right or right to the left without replacing any fragment with another. Is this somehow possible?
you could use ViewPager for that. And on your adapter class you will have to switch between the fragments via getItem(). Eclipse/new AndroidProject/ swipe with/out tabs. And check the example code generated by Android.
edit:
create xml file call it main_activity.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FAFAFA"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#36466E" />
create a class call it Main
public class Main extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Context ctx;
static MySQLiteHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case 0:
fragment = new GridApp();
break;
case 1:
fragment = new ListApp();
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Select App";
case 1:
return "Selected Apps";
}
return null;
}
}
}
now create a class called GridApp and ListApp
GridApp class.
public class GridApp extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridpp,
container, false);
}
}
ListApp class
public class GridApp extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listapp,
container, false);
}
}
and you are done.

Fragment in FragmentPagerAdapter

I want a tab with 4 scrollable tabs in a class. I implemented the following example and it works:
mAdapter = new MyAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
...
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS; //NUM_ITEMS=4
}
#Override
public ArrayListFragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return "TAB1";
case 1:
return "TAB2";
case 2:
return "TAB3";
case 3:
return "TAB4";
default:
return "ERROR";
}
}
}
...
public static class ArrayListFragment extends ListFragment {
int mNum;
static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
switch(mNum) {
case 0:
View v0 = inflater.inflate(R.layout.fragment_pager_list, container, false);
return v0;
case 1:
View v1 = inflater.inflate(R.layout.fragment_pager_list, container, false);
return v1;
case 2:
View v2 = inflater.inflate(R.layout.fragment_pager_list, container, false);
return v2;
case 3:
View v3 = inflater.inflate(R.layout.fragment_pager_list, container, false);
return v3;
default:
View vd = inflater.inflate(R.layout.fragment_pager_list, container, false);
return vd;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Titles));
}
//Titles={"TAB1", "TAB2", "TAB3", "TAB4"}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
}
}
where fragment_pager_list layout that I put in each view is the following:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:drawable/gallery_thumb">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="HELLO WORLD"/>
<!-- The frame layout is here since we will be showing either
the empty view or the list view. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<!-- Here is the list. Since we are using a ListActivity, we
have to call it "#android:id/list" so ListActivity will
find it -->
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
<!-- Here is the view to show if the list is emtpy -->
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="No items."/>
</FrameLayout>
The problem is that I want to put a different layout in each view for each tab.
I tried to modify the code so that "ArrayListFragment" inherits from "Fragment" instead of "ListFragment" to load layouts that do not contain "ListView" but "RelativeLayout" or "LinearLayout", but can not get it to work.
Please, if anyone can help me, I need to load different views on the tabs and that they contain other elements than ListView.
Thank you very much.
You'd better make each fragment for different layout.
You can add addFragment(Fragment fragment) method to MyAdapter.
mAdapter = new MyAdapter(getSupportFragmentManager());
for(int i=0; i<4; i++) {
Fragment fragment = null;
switch(i) {
case 0:
fragment = FirstFragment.newInstance();
break;
case 1:
fragment = SecondFragment.newInstance();
break;
case 2:
fragment = ThirdFragment.newInstance();
break;
case 3:
fragment = FourthFragment.newInstance();
break;
}
mAdapter.addFragment(fragment);
}
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
MyAdapter : Adapter is a simple container.
public static class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList;
public MyAdapter(FragmentManager fm) {
super(fm);
mFragmentList = new ArrayList<Fragment>();
}
publid void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return ((CustomFragment) mFragmentList.get(position)).getPageTitle();
}
}
CustomFragment : Put common methods for each fragments.
public abstract class CustomFragment extends Fragment {
public abstract Fragment newInstance();
public abstract String getPageTitle();
}
FirstFragment : Inflate different layout for each fragments.
public class FirstFragment extends CustomFragment {
#Override
public Fragment newInstance() {
Fragment f = new FirstFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.LAYOUT_ID_FOR_FIRST_FRAGMENT, container, false);
// Some codes for layout such as findViewById
return view;
}
#Override
public String getPageTitle() {
// return TITLE_FOR_FRAGMENT
}
}
I hope this answer will help you.

Categories

Resources