PagerView with fragment - android

I have a ListView with books. When I click the row I am able to see book details in new fragment, something similar like in Training Android. I would like to slide books (right -> next element from the list, left <- previous element from the list).
PROBLEM
How to integrate ViewPager with fragements? When I click element on the list FragmentTransaction is invoke.
Activity:
public class MyActivity extends FragmentActivity implements RecyclerViewFragment.OnFragmentInteractionListener {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final Fragment mFragment = new RecyclerViewFragment();
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container, mFragment)
.commit();
}
}
#Override
public void onFragmentInteraction(int id) {
Log.d("Element Id ", String.valueOf(id));
PagerViewFragment newFragment = new PagerViewFragment();
Bundle args = new Bundle();
args.putInt(PagerViewFragment.ARG_POSITION, id);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
How to inform fragment that should change the view?
Should I use this code?
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
EDIT
After ILovemyPancho answer stack again. java.lang.NullPointerException:
PagerViewFragment:
public class PagerViewFragment extends Fragment {
final static String ARG_POSITION = "position";
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
public PagerViewFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewRoot = (ViewGroup) inflater.inflate(R.layout.pager_fragment, container, false);
mPager = (ViewPager) container.findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mPager.setAdapter(mPagerAdapter); //line 39. Error is here
return viewRoot;
}
#Override
public void onStart() {
super.onStart();
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
PagerViewFragment frag = new PagerViewFragment();
Bundle args = new Bundle();
args.putString("BookTitle", "FD");
DummyContent dummyContent = new DummyContent(); //elements
TextView street = (TextView) getView().findViewById(R.id.street_article);
street.setText(dummyContent.murals.get(position).getStreet());
TextView artist = (TextView) getView().findViewById(R.id.artist_article);
artist.setText(dummyContent.murals.get(position).getArtists().get(0).getName());
frag.setArguments(args);
return frag;
}
#Override
public int getCount() {
return DummyContent.murals.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
MyActivity:
public class MyActivity extends FragmentActivity implements RecyclerViewFragment.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final Fragment mFragment = new RecyclerViewFragment();
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container, mFragment)
.commit();
}
}
#Override
public void onFragmentInteraction(int id) {
Log.d("Element Id ", String.valueOf(id));
PagerViewFragment newFragment = new PagerViewFragment();
Bundle args = new Bundle();
args.putInt(PagerViewFragment.ARG_POSITION, id);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
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" />
pager_fragmet.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/blank_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.szymon.fragmentexample.BlankFragment">
<TextView
android:id="#+id/street_article"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:text="hello_blank_fragment"
android:textSize="23dp" />
<TextView
android:id="#+id/artist_article"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/street_article"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:text="hello_blank_fragment"
android:textSize="15dp" />
<TextView
android:id="#+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/artist_article"
android:layout_marginLeft="50dp"
android:layout_marginTop="100dp"
android:text="here will be the picture"
android:textSize="15dp" />
</RelativeLayout>
</ScrollView>
I got an error:
java.lang.NullPointerException
at com.example.szymon.recyclerview.PagerViewFragment.onCreateView(PagerViewFragment.java:39)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)

Ok, So you have an Activity dislaying a ListFragment (RecyclerViewFragment). When you click a list item, ListFragment is replaced by PagerViewFragment showing the details of the book.
Try this. Create a fragment containing the ViewPager. This fragment is going to replace your ListFragment when an item is clicked. Lets call it BookDetailsContainer, and is going to receive the list item id:
BookDetailsContainer newFragment = BookDetailsContainer.newInstance(id);
Inside this fragment you set the viewpager:
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mPager.setAdapter(mPagerAdapter);
getChildFragmentManager() is needed by the ViewPager to handle the nested fragments (the PagerViewFragment inside the BookDetailsContainer). And since you passed the list position id to the BookDetailsContainer, you can set the position:
mPager.setCurrentItem(positionId);
In your ScreenSlidePagerAdapter, you are going to create a PagerViewFragment instance,
get the information to display from your data source (array, cursor...) based on the
position, pass that data to the fragment using a Bundle, and return the fragment:
#Override
public Fragment getItem(int position) {
PagerViewFragment frag = new PagerViewFragment();
Bundle args = new Bundle();
//get data from your data source based on the "position"
args.putString("BookTitle", ...);
args.putString("BookAuthor", ...);
...
frag.setArguments(args);
return frag;
}
And that's basically how you can do it.

Related

Content does not load in tab layout fragment when the parent fragment is replacing other fragment

I have a MainActivIty and it supports two fragments i.e Home and Profile.Home has a TabLayout which in turn has three fragments Trending,Followed and Nearby.
So the issue is when Home is first time loaded it shows the content of the Tab fragments and slider of tab layout moves properly but when I got to profile and then to home then the tab layout fragments do not load and while swiping left to right slider does not move smoothly.Here is the code.
public class MainActivity extends AppCompatActivity {
ImageButton home_btn,myProfile_btn;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
TextView txt_action_bar;
Home home;
ProfileFragment profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
home_btn=(ImageButton)findViewById(R.id.home_btn) ;
discover_btn=(ImageButton)findViewById(R.id.discover_btn) ;
myProfile_btn=(ImageButton)findViewById(R.id.profile_btn) ;
notification_btn=(ImageButton)findViewById(R.id.notification_btn) ;
plus_btn=(ImageButton)findViewById(R.id.btn_plus) ;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
txt_action_bar = (TextView)findViewById(R.id.toolbar_title);
displayMetrics = getResources().getDisplayMetrics();
Typeface custom_font = Typeface.createFromAsset(getAssets(),"fonts/NoteworthyLight.ttf");
txt_action_bar.setTypeface(custom_font);
setSupportActionBar(toolbar);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
home = new Home();
profile = new ProfileFragment();
fragmentTransaction.add(R.id.main_fragment_container,home,"home");
fragmentTransaction.commit();
}
public void onClickHome(View view)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment_container,home,"home");
fragmentTransaction.commit();
}
public void onClickMyProfile(View view)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment_container,profile,"profile");
fragmentTransaction.commit();
}
}
Home.java
public class Home extends Fragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public Home() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_home, container, false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) view.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
return view;
}
FollowedFragment.java
public class FollowedFragment extends Fragment {
public FollowedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.feeds_list, container, false);
new DownloadFollowedFeeds().execute();
return rootView;
}
fragment_home.xml
<LinearLayout android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
style="#style/TabNameStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/medium_turquoise"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="fill_parent"/>
SectionPagerAdapter.java
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[] { "Trending", "Followed","Nearby" };
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).
Log.i("tag","number"+String.valueOf(position));
if(position==0) return new TrendingFragment();
else if(position==1) return new FollowedFragment();
else return new NearbyFragment();
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
As answered here:
When you are creating the view adapter in Home.java:
instead of
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
you should do,
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());

Android - Navigation drawer fragments

I have implemented navigation drawer in my android app. but now I want to be able to change the layout using fragments when the user clicks any list item in the navigation bar.
Here is what I have got so far:
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
Java File
public class MainActivity extends Activity {
final String[] data ={"one","two","three"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
}
});
drawer.closeDrawer(navList);
}
});
}
}
Using the above code, I implemented navigation drawer in my app and I see "one", "two" and "Three" list items in the navigation drawer but nothing happens when I click on them except the drawer closes.
So, my question is :
How do I add the fragment functionality to the above given code?
I am beginner. Thanks in advance!
On click have
selectItem(pos);
Then
public void selectItem(int position)
{
switch(position)
{
case 0:
// fragment1
// use fragment transaction and add the fragment to the container
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment = new Fragment1();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.commit();
break;
case 1:
// fragment2
break;
case 2:
// fragment2
break;
}
}
use This:
public class MenuFragmentActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_layout);
addFragments(new Sample(), false, false,
AndyConstants.CONTENT_PAGE);
}
public void addFragments(Fragment fragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.anim.fragment_from_right,
R.anim.fragment_from_left, R.anim.fragment_from_right,
R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
For Fragment:
public class Sample extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.page, container, false);
return view;
}
}
After generate a Navigation Drawer Activity by File->New->Activity->Navigation Drawer Activity, here are 3 steps
First, go to app_bar_main.xml then
replace
<include layout="#layout/content_main"/>
by
<FrameLayout
android:id="#+id/frame_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
Second, go to MainActivity -> onNavigationItemSelected then modify it like
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = CameraFragment.newInstance();
} else if (id == R.id.nav_gallery) {
fragment = GalleryFragment.newInstance();
} else if (id == R.id.nav_slideshow) {
fragment = SlideShowFragment.newInstance();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_content, fragment).commit();
setTitle(item.getTitle());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Finally, create Fragment class, example a Fragment
public class CameraFragment extends Fragment{
public static CameraFragment newInstance() {
Bundle args = new Bundle();
CameraFragment fragment = new CameraFragment();
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_camera, null, false);
return rootView;
}
}
Demo project

Send data from activity to fragment using Tab Layout with Swipeable Views in Android

I created a Tab Layout with Swipeable Views using this tutorial. I'm trying to pass a string from Activity to Fragment. I read about fragment communication and couple other topics on stackoverflow but still i get null pointer exception. Here's my code:
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final int REQUEST_CODE_EMAIL = 1;
String password, email;
ViewPager viewPager;
TabsPagerAdapter tabsPagerAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
viewPager.setAdapter(tabsPagerAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
actionBar.addTab(actionBar.newTab().setText("Głowna").setTag("main").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Rachunki").setTag("bills").setTabListener(tabListener));
Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();
}
activity_main.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">
</android.support.v4.view.ViewPager>
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
public TabsPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
#Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new EnterExitFragment();
case 1:
return new BillsFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
EnterExitFragment.java
public class EnterExitFragment extends Fragment{
TextView tvFloor1, tvFloor2, tvEmail;
Button btnSend;
Integer floorId, segmentId, spaceId, ticketId;
String floorName, segmentName, spaceName;
String email;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);
tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
new FloorFreeSpaces(EnterExitFragment.this).execute();
btnSend = ((Button)rootView.findViewById(R.id.btnSend));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Floor(EnterExitFragment.this).execute();
email = getArguments().getString("email"); //line 55
tvEmail.setText(email);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
activity_enter_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textFloor1"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textFloor2"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="354dp"
android:layout_height="93dp"
android:text="Email:"
android:id="#+id/textEmail"
android:layout_gravity="center_horizontal|bottom" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="SEND"
android:id="#+id/btnSend"
android:layout_gravity="center_horizontal|bottom" />
</LinearLayout>
error log
java.lang.NullPointerException
at com.carpark.EnterExitFragment$1.onClick(EnterExitFragment.java:55)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17722)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5303)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Has anyone solution for my problem? :)
EDIT: My suggestion is to make the following constructor which takes Bundle object as an argument:
public EnterExitFragment(Bundle bundle) {
super();
setArguments(bundle);
}
and call that constructor with bundle object as the argument instead of the default one in your program. That way you're sure to add the bundle before you attach it to your Activity.
Additionally, if that doesn't work, add a Bundle attribute to your EEF class, initialize it within your constructor and refer to it rather than getArguments() method:
public class EnterExitFragment extends Fragment{
TextView tvFloor1, tvFloor2, tvEmail;
Button btnSend;
Integer floorId, segmentId, spaceId, ticketId;
String floorName, segmentName, spaceName;
String email;
Bundle args;
public EnterExitFragment(Bundle bundle) {
super();
args = bundle;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);
tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
new FloorFreeSpaces(EnterExitFragment.this).execute();
btnSend = ((Button)rootView.findViewById(R.id.btnSend));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Floor(EnterExitFragment.this).execute();
email = args.getString("email"); //line 55
tvEmail.setText(email);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
I do not see that you set your argument to fragment. If you did, but you forgotten to write please inform me...
Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
enterExitFragment.setArguments(bundle); // This line is needed...
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();

recreate view of fragment via button

I've got a FragmentActivity which show the correct fragment, using a ViewPager. I added a Fragment StatePagerAdapter to the ViewPager. If I push a button at a Fragment, it should be recreated (onCreateView should be called again). The fragments are articles and if the user is offline, I'll show him "please check your networkconnection" and a button to reload. The button called a method in the FragmentActivity, but I don't know how implement it. Maybe I can destroy and recreate the current Fragment?
here the important part of the FragmentActivity:
private ArrayList<Fragment> fragments;
protected void onCreate(Bundle savedInstanceState)
{
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article_page_slider);
...
pages = datahandler.getCount(...);
viewPager = (ViewPager) findViewById(R.id.articlePager);
PagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(startPosition);
fragments = new ArrayList<Fragment>(pages);
}
public void reloadData(View v)
{
// TODO
((ArticlePageFragment)fragments.get(viewPager.getCurrentItem())).refresh();
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
public ScreenSlidePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = new ArticlePageFragment();
Bundle args = new Bundle();
...
fragment.setArguments(args);
fragments.add(position, fragment);
return fragment;
}
public int getCount()
{
return pages;
}
}
and the Fragment itself:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
activity = getActivity();
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_article_page, container, false);
CacheDataHandler cdh = new CacheDataHandler(activity);
cdh.open();
String htmlData = cdh.loadData();
rootView.findViewById(R.id.btn_reload_article_data).setVisibility(View.GONE);
webView = ((WebView) rootView.findViewById(R.id.articleFragment));
refresh();
...
return rootView;
}
public void refresh()
{
...
if (htmlData == null)
{
rootView.findViewById(R.id.btn_reload_article_data).setVisibility(View.VISIBLE);
webView.loadData(defaultdata,"text/html", "UTF-8");
}
else
{
webView.loadData(htmlData,"text/html", "UTF-8");
}
}
and the fragment_article_page.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/articleFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/btn_reload_article_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="reloadData"
android:text="#string/btn_txt_reload_data"
android:visibility="gone" />
</RelativeLayout>
EDIT
added a private ArrayList<Fragment> fragments in FragmentActivity and transfer the code for manipulating the view in an extra refreshMethod, look ahead. All works fine, if I only click on the first or second Fragment (index 0 and 1). Otherwise I get an IndexOutOfBoundsException. How to initialize and fill the ArrayList?

How to create an Android Tabbed Dialog containing fragments?

Can anyone point me to an example or show me how to create a simple Tabbed Dialog in Android where the contents of each tab are Fragments? All the examples/tutorials I have found are about Fragments and Tabs, but nothing specific to DialogFragments.
The documentation for FragmentTabHost shows how to create tabs within normal fragments using getChildFragmentManager(). I'm assuming this should also work when the fragment is a DialogFragment but when I try it I get:
java.lang.IllegalStateException: Fragment does not have a view at android.support.v4.app.Fragment$1.findViewById(Fragment.java:1425)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:901)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
...
Here's my code for setting up the view (which is then passed to AlertDialog.setView()):
private void setupView(View v) {
mTabHost = (FragmentTabHost) v.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
MyDialogFragment.class, null);
}
Spent a lot of time to get it working, but no luck. The only solution I found is create dummy fragment tabhost and use viewpager with fragments instead of tabhost fragments
voters_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
>
<android.support.v4.app.FragmentTabHost
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabs"
>
</android.support.v4.app.FragmentTabHost>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
</LinearLayout>
Dialog class, the trick is use onCreateView not onCreateDialog
public class VotersDialog extends DialogFragment {
private FragmentTabHost mTabHost;
private ViewPager viewPager;
private VotersPagerAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.voters_dialog, container);
getDialog().setTitle(getArguments().getString("title"));
mTabHost = (FragmentTabHost) view.findViewById(R.id.tabs);
mTabHost.setup(getActivity(), getChildFragmentManager());
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Плюсов"), Fragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Минусов"), Fragment.class, null);
adapter = new VotersPagerAdapter(getChildFragmentManager(), getArguments());
adapter.setTitles(new String[]{"Плюсов", "Минусов"});
viewPager = (ViewPager)view.findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
mTabHost.setCurrentTab(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String s) {
int i = mTabHost.getCurrentTab();
viewPager.setCurrentItem(i);
}
});
return view;
}
public class VotersPagerAdapter extends FragmentPagerAdapter {
Bundle bundle;
String [] titles;
public VotersPagerAdapter(FragmentManager fm) {
super(fm);
}
public VotersPagerAdapter(FragmentManager fm, Bundle bundle) {
super(fm);
this.bundle = bundle;
}
#Override
public Fragment getItem(int num) {
Fragment fragment = new VotersListFragment();
Bundle args = new Bundle();
args.putSerializable("voters",bundle.getSerializable( num == 0 ? "pros" : "cons"));
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
public void setTitles(String[] titles) {
this.titles = titles;
}
}
public static class VotersListFragment extends ListFragment {
List<String> voters;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
voters = (ArrayList) getArguments().getSerializable("voters");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, voters);
setListAdapter(adapter);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), ProfileActivity_.class);
String login = voters.get(i);
intent.putExtra("login", Utils.encodeString(login.substring(0, login.indexOf("(")).trim()));
startActivity(intent);
}
});
}
}
}
Here is result, now you can press tabs or swipe fragments
I was looking for the same solution but nothing worked out for me so I built my own Android tabbed dialog containing fragments. might be it may help someone.
you can checkout the complete source code from here
You should use a DialogFragment, TabLayout and ViewPager. For instance, your dialog fragment's view may look like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/masterViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Build your adapter and make sure you override the getPageTitleMethod, e.g:
public class CustomAdapter extends FragmentPagerAdapter {
List<Fragment> mFragmentCollection = new ArrayList<>();
List<String> mTitleCollection = new ArrayList<>();
public CustomAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(String title, Fragment fragment)
{
mTitleCollection.add(title);
mFragmentCollection.add(fragment);
}
//Needed for
#Override
public CharSequence getPageTitle(int position) {
return mTitleCollection.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentCollection.get(position);
}
#Override
public int getCount() {
return mFragmentCollection.size();
}
}
In the OnCreateView of your dialog, you should setup your viewpager with the tabLayout:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.dialog_sample,container,false);
tabLayout = (TabLayout) rootview.findViewById(R.id.tabLayout);
viewPager = (ViewPager) rootview.findViewById(R.id.masterViewPager);
CustomAdapter adapter = new CustomAdapter(getChildFragmentManager());
adapter.addFragment("Boy",CustomFragment.createInstance("John"));
adapter.addFragment("Girl",CustomFragment.createInstance("Stacy"));
adapter.addFragment("Robot",CustomFragment.createInstance("Aeon"));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return rootview;
}
I have a blog post written on it here: here.
Try using DialogFragment instead and on your dialogfragment layout include a LinearLayout for fragmentTransaction.
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
String Tag = fragment.getClass().getSimpleName();
t.replace(R.id.llTabFragmentContainer, fragment, Tag);
t.commit();
fragment is your tab fragment.
cheeers

Categories

Resources