How to communicate from Mainactivity to Fragment using callback interface? - android

I'm having navigation drawer with four menu's and each menu has own fragments
, Inside first fragment has view pager sliding tab with 2 fragments,
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="4dp" />
</android.support.design.widget.AppBarLayout>
////////////// Here I'm replacing each fragments ////////////////
<FrameLayout
android:id="#+id/main_content_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_done"
android:visibility="gone"/>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
ManinActivity- DrawerSelection
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
fragmentClass = Home_Tab_Fragment.class;
break;
case R.id.nav_myorders:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_myoffers:
fragmentClass = ThirdFragment.class;
break;
case R.id.nav_notification:
fragmentClass = FourthFragment.class;
break;
}
fragment = (Fragment) fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content_framelayout, fragment).commit();
mDrawerLayout.closeDrawers();
}
HomeTabFragment
public class Home_Tab_Fragment extends Fragment {
private FragmentActivity myContext;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_viewpager, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SlidingTabAdapter adapter = new SlidingTabAdapter(getChildFragmentManager());
adapter.addFragment(new FirstTabFragment(), "First TAB");
adapter.addFragment(new SecondTabFragment(), "Second Tab");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
tabLayout.setVisibility(View.VISIBLE);
tabLayout.setupWithViewPager(viewPager);
}
}
SlidingTabAdapter
public class SlidingTabAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public SlidingTabAdapter(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);
}
}
layout_viewpager.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FirstFragment
public class FirstTabFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
getActivity().setTitle("Foodies");
return rootView ;
}
public void updateFirstFragmentValues(){
//Doing some operations
}
}
Inside MainActivity , I want to call FirstTabFragment method [updateFirstFragmentValues()]
I tried adding TAG in FirstTabFragment ,
public static final String TAG ="FirstTabFragment.TAG";
Then I invoked in MainActivity like below , but Fragment always null.
public void invokeMethodFromFirstTabFragment() {
FragmentManager fm = this.getSupportFragmentManager();
FirstTabFragment fb=(FirstTabFragment)fm.findFragmentByTag(FirstTabFragment.TAG);
if (null != fb) {
fb.updateFirstFragmentValues();
}else{
L.m("Fragment is null===========");
}
}
Kindly advise , How to call "FirstTabFragment" method from inside "MainActivity"
Please note FirstTabFragment is not added directly to MainActivity ,
its added through "Home_Tab_Fragment".

Alright, reading all of the responses of yours, I get that you just simply need to pass data to a fragment upon creation and be able to execute some of Fragment's methods. Ok, simple enough:
IMessageFragment interface
public interface IMessageFragment {
/**
* Method to receive new message text
* #param text Message text to receive
*/
void updateMessageText(String text);
}
MessageFragment
public class MessageFragment extends Fragment implements IMessageFragment {
/**
* Bind views using ButterKnife
*/
#BindView(R.id.textView) TextView mTextView;
/**
* Bundle data
*/
private String mMessageText;
/**
* Unique id of bundle data
*/
private static final String MESSAGE_EXTRA_KEY = "f_message";
/**
* New fragment pattern. This is pretty much all the magic PLUS this
* looks by far better than `new Fragment()` upon instatiation
*/
public static MessageFragment newFragment(String message) {
// 1. Create new fragment
MessageFragment auctionFragment = new MessageFragment();
// 2. Create bundle for fragment params
Bundle args = new Bundle();
// 3. Put position
args.putString(MESSAGE_EXTRA_KEY, message);
// 4. Set arguments
auctionFragment.setArguments(args);
return auctionFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tutorial_fragment, container, false);
/**
* Bind views
*/
ButterKnife.bind(this, view);
// Update UI
updateUI();
return view;
}
/**
* Method to update value of mTextView
*/
private void updateUI() {
if(!mMessageText.equals("")) {
mTextView.setText(mMessageText);
}
}
#Override
public void updateMessageText(String text) {
mMessageText = text;
updateUI();
}
}
Stuff is pretty simple and the interface exists only for good code style and to support design patterns.

Edit:
You cannot directly access FirstTabFragment method from your MainActivity. Firstly you have to call Home_Tab_Fragment method from activity. Then from that method you can call FirstTabFragment method.
Here is strategy:
Step 1: Home_Tab_Fragment to FirstTabFragment communication
define an interface like this
public interface IHomeToFirstFragmentController{
void firstFragmentMethod();
}
Now implements the IHomeToFirstFragmentController in your FirstTabFragment. then you have to implements the firstFragmentMethod().
#overrride
void firstFragmentMethod(){
}
Call this firstFragmentMethod method from Home_Tab_Fragment using this way
YOUR_fragmentInstance.firstFragmentMethod();
Step 2: Activity to Home_Tab_Fragment:
define an interface like this
public interface IActivityToHomeTabController{
void callFirstFragment();
}
Now implements the IFragmentController in your Home_Tab_Fragment. then you have to implements the callFirstFragment().
#overrride
void callFirstFragment(){
YOUR_fragmentInstance.firstFragmentMethod();
}
Edit 2:
Call fragment using this way
((IFragmentController)YOUR_fragmentInstance).firstFragmentMethod();
Hope this will give you an idea about this topics. For more info visit this answer

First for all, you create interface :
public interface CallBackListener{
void onCallBack();
}
In Fragment
public MyFragment extends Fragment{
private CallBackListener mCallBack;
#Override
public void onAttach(Context context) {
AppCompatActivity activity;
if (context instanceof AppCompatActivity) {
activity = (AppCompatActivity) context;
try {
mCallBack= (CallBackListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " class must be implement" +
" OnBackFragmentListener");
}
}
super.onAttach(context);
}
}
Use :
mCallBack.onCallBack();
And in Activity, you must implements interface :
public MyActivity extends AppCompatActivity implements CallBackListener{
#Override
public void onCallBack(){
// Do somethings here...
}
}

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.

Layout for tablets using two fragments

I am doing a sample project as an excercise and want to display two fragments in the same activity when dealing with tablets(7' and 10').
So what I have so far is this.
As you can see I can display the data of my recyclerview in the left (static) fragment. However the right fragment is empty.
So I have two questions.
1) How to display by default in the right fragment the data of the first row of recyclerview?(ie image and article)
2) How to implement the click listener and update the right fragment?
Here is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private boolean mTwoPane;
private static final String DETAIL_FRAGMENT_TAG = "DFTAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.detailed_match_reports)!=null) {
mTwoPane = true;
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.detailed_match_reports, new DetailedActivityFragment(),DETAIL_FRAGMENT_TAG)
.commit();
}else{
mTwoPane = false;
}
}
}
}
layout/activity_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context="theo.testing.androidservices.activities.MainActivity"
tools:layout="#android:layout/list_content" />
layout-sw600dp/activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
tools:context="theo.testing.androidservices.activities.MainActivity">
<fragment
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#android:layout/list_content" />
<FrameLayout
android:id="#+id/detailed_match_reports"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4" />
</LinearLayout>
MainActivityFragment
public class MainActivityFragment extends Fragment {
public static final String TAG = "AelApp";
public static ArrayList<MyModel> listItemsList;
RecyclerView myList;
public static MatchReportsAdapter adapter;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMatchReport();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Match Report");
View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
listItemsList = new ArrayList<>();
myList = (RecyclerView)rootView.findViewById(R.id.listview_match_reports);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
myList.setHasFixedSize(true);
myList.setLayoutManager(linearLayoutManager);
adapter = new MatchReportsAdapter(getActivity(), listItemsList);
myList.setAdapter(adapter);
return rootView;
}
public void updateMatchReport(){
Intent i = new Intent(getActivity(), MatchReport.class);
getActivity().startService(i);
}
}
First let me answer the second question. To show a fragment on the right side of the screen add something like this (note how I'm using that id of the frame layout to replace the fragment):
Fragment fragment = new MyRightSideFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.detailed_match_reports, fragment).commit();
Now, for the first question, you need to implement click listener, you can find an example here.
public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
showDetail(position);
}
});
}
}
Notice that I'm using the tag of the view to identify the position (so somwhere in your onBindViewHolder code you must set this tag).
public function showDetail(int position) {
... show fragment por position
}
and finally, when your in your OnCreateView or somewhere in your setup code, call showDetail(0).

Android TabLayout ViewPager not inflating tab fragment on backstack

I've got a tab view set up that that has custom fragments for each tab using a viewpager. This is my code:
Holding Fragment
public class FragInboxMainView extends Fragment implements CGFragment {
private CGController controller;
private CGFragment thisFragment;
#Bind(R.id.inboxViewPager)ViewPager inboxViewPager;
#Bind(R.id.inboxTabs)TabLayout inboxTabLayout;
#Bind(R.id.inbox_progress_wheel)ProgressWheel inboxProgressWheel;
public FragInboxMainView(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_inbox_mainview, container, false);
ButterKnife.bind(this, rootView);
thisFragment = this;
Globals g = Globals.getInstance();
/** Show loading spinner */
this.inboxProgressWheel.setBarColor(ContextCompat.getColor(controller.getContext(), g.getUserObject().getUserThemeColor()));
this.inboxProgressWheel.setVisibility(View.VISIBLE);
/** Display the profile information based off the ID */
controller.displayInbox(thisFragment);
return rootView;
}
public void hideProgressSpinner() {
this.inboxProgressWheel.setVisibility(View.GONE);
}
public ViewPager getInboxViewPager() {
return this.inboxViewPager;
}
public TabLayout getInboxTabLayout() {
return this.inboxTabLayout;
}
}
Its layout file
<?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:wheel="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/inboxTabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
<com.pnikosis.materialishprogress.ProgressWheel
android:id="#+id/inbox_progress_wheel"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
wheel:matProg_barColor="#5588FF"
wheel:matProg_progressIndeterminate="true"
android:visibility="gone"/>
<android.support.v4.view.ViewPager
android:id="#+id/inboxViewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
Tab fragment and its inflation file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.baoyz.widget.PullRefreshLayout
android:id="#+id/tabPullRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/tabRecyclerHolder"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:clipToPadding="false"
android:layout_centerInParent="true"/>
</com.baoyz.widget.PullRefreshLayout>
<com.melnykov.fab.FloatingActionButton
android:id="#+id/tabFab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:src="#mipmap/ic_add_white"/>
</android.support.design.widget.CoordinatorLayout>
public class TabRecyclerHolder extends Fragment {
#Bind(R.id.tabRecyclerHolder) RecyclerView tabRecyclerHolder;
#Bind(R.id.tabPullRefresh) PullRefreshLayout tabPullRefresh;
#Bind(R.id.tabFab) FloatingActionButton recyclerFab;
private String tabTitle = "Title";
public TabRecyclerHolder(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_recycler_holder, container, false);
ButterKnife.bind(this, rootView);
recyclerFab.hide(false);
tabPullRefresh.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
return rootView;
}
public RecyclerView getTabRecyclerHolder() {
return this.tabRecyclerHolder;
}
public FloatingActionButton getRecyclerFab() {
return this.recyclerFab;
}
public String getTabTitle() {
return this.tabTitle;
}
public void setTabTitle(String title) {
this.tabTitle = title;
}
public PullRefreshLayout getTabPullRefresh() {
return this.tabPullRefresh;
}
}
My tab adapter
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private CGController controller;
private List<Object> items;
public TabPagerAdapter(FragmentManager fm, CGController controller, List<Object> items) {
super(fm);
this.controller = controller;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Fragment getItem(int num) {
return (TabRecyclerHolder)items.get(num);
}
#Override
public String getPageTitle(int num){
return ((TabRecyclerHolder)items.get(num)).getTabTitle();
}
}
The processing code
public void viewInbox() {
/** Set up the views */
receivedHolder = new TabRecyclerHolder();
receivedHolder.setTabTitle(Constants.TAB_INBOX_RECEIVED);
sentHolder = new TabRecyclerHolder();
sentHolder.setTabTitle(Constants.TAB_INBOX_SENT);
tabs.add(receivedHolder);
tabs.add(sentHolder);
/** Set up the tabs */
final ViewPager inboxViewPager = inboxFragment.getInboxViewPager();
TabLayout inboxTabLayout = inboxFragment.getInboxTabLayout();
/** Set the adapter for the view pager */
inboxViewPager.setAdapter(new TabPagerAdapter(inboxFragment.getChildFragmentManager(), controller, tabs));
/** set up the tab look and feel */
inboxTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
inboxTabLayout.setTabMode(TabLayout.MODE_FIXED);
inboxViewPager.setOffscreenPageLimit(3);
inboxViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(inboxTabLayout));
inboxTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
inboxViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
/** And, display! */
inboxTabLayout.setupWithViewPager(inboxViewPager);
receivedAdapter = new RecyclerListAdapter(controller, items);
final RecyclerView receivedList = receivedHolder.getTabRecyclerHolder();
receivedList.setLayoutManager(new LinearLayoutManager(controller.getContext()));
receivedList.setAdapter(receivedAdapter);
}
There is some code i've missed out but its not pertanent to the question.
The code works perfectly when initially viewing the fragment. However since my application contains a single activity and just replaces a content view for each fragment navigated to, each fragment is added to the back stack and then popped when the back button is pressed. My issue is that when navigating back to this fragment the view inside the tab isn't being inflated, which means that no elements can be accessed (and therefore the app crashes while trying to display the data in the recyclerview etc).
I have had a look at this question: TabLayout ViewPager Not Loading When Using Backstack and implemented its suggestion (using getChildFragmentManager() when setting up the pager adapter) however that has not fixed my issue.
Help would be appreciated!
Change this public View onCreateView(LayoutInflater inflater,... to public void onViewCreated (View view, Bundle savedInstanceState)
so you are going to have something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_recycler_holder, container, false);
}
then
#Override
public void onViewCreated (View view, Bundle savedInstanceState){
ButterKnife.bind(this, view);
recyclerFab.hide(false);
tabPullRefresh.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
...
see if it helps
Extend FragmentStatePagerAdapter in TabPagerAdapter as
FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

How to display fragment in viewpager, in fragment class?

I have a activity which contains of navigation drawer, in that class my navigation items point to fragment classes, In one of the fragment classes i am using a dynamic view pager to display items, but how can i use fragment manager of fragment class as a argument of view pager which needs fragment argument of fragment activity or activity, Need some solutions.
I'm doing something similar right now. I only have the the ViewPager below the navigation drawer, but if you have a more complicated layout the same principal should work.
To start, I have the activity layout (most of this was generated by Android Studio)
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.you.yourapp.YourActivity">
<FrameLayout android:id="#+id/your_container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.you.yourapp.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
The activity uses the FragmentManager to swap in another fragment that contains the ViewPager into the FrameLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your);
...
Fragment fragment = YourFragment.newInstance(Bundle args);
getSupportFragmentManager()
.beginTransaction().replace(R.id.your_container, fragment)
.commit();
}
The Fragment that has the ViewPager is simple
<android.support.v4.view.ViewPager android:id="#+id/your_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
in YourFragment.java implement your FragmentPagerAdapter(you could do this as an inner class, but I ran into problems with static allocation, plus this is cleaner)
public class YourFragment extends android.support.v4.app.Fragment {
private ViewPager mPager;
public YourFragment() {
}
public static TaskFragment newInstance(Uri uri, String outlineText) {
TaskFragment fragment = new YourFragment();
Bundle args = new Bundle();
//set args
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 rootView = inflater.inflate(R.layout.fragment_your, null);
mPager = (ViewPager) rootView.findViewById(R.id.your_view_pager);
TaskPagerAdapter adapter = new TaskPagerAdapter(getFragmentManager());
mPager.setAdapter(adapter);
return rootView;
}
...
private class YourPagerAdapter extends FragmentStatePagerAdapter {
public YourPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return count; //however you get the count
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
//set the arguments for your page
return PageFragment.newInstance(args);
}
}
}
ETA:
So now implement a custom interface for your navigation drawer callbacks
...
private NavigationDrawerCallbacks mCallbacks
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (NavigationDrawerCallbacks) activity;
}
...
#Override
public void onClick(View view) { //whatever your click listener is
Fragment fragment = getFragmentSomehow(); //get your fragment
mCallbacks.onNavigationItemSelected(fragment);
}
...
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(Fragment fragment);
}
Now have YourActivity implement this interface
public class YourFragment extends Activity
implements NavigationDrawerCallbacks
{
...
#Override
public void onNavigationDrawerItemSelected(Fragment fragment) {
getSupportFragmentManeger()
.beginTransaction()
.replace(R.id.you_container, fragment)
.commit();
}
...
}
I think this is what you mean to do.
Hope this helps

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.

Categories

Resources