I'm trying to create VeiwPager inside a Fragment using FragmentStatePagerAdapter.
it displays the first fragment but after scrolling to the second fragment there is just white fragment (even on scrolling back to the first fragment)
I've tried to use PagerAdapter and set pictures without fragment but the result is same.
is there RAM problem ? what can I do to solve it?
Home fragment(contains ViewPager) :
private void initSlideShow(View view){
VPImageSlider = (ViewPager16by9) view.findViewById(R.id.VPImageSlider);
sliderDotsPanel = (LinearLayout) view.findViewById(R.id.SliderDots);
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_1);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_2);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_3);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_4);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_5);
VPImageSlider.setAdapter(vpImageSliderAdapter);
}
ViewPager Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import iranelab.samsoft.net.iranelab.Classes.ImageView16by9;
import iranelab.samsoft.net.iranelab.R;
public class ViewPagerFragment extends Fragment {
private static final String ARG_PARAM4 = "imageTest";
private int imageTest;
public ViewPagerFragment() {}
public static ViewPagerFragment newInstance(String imageId, String type, String text,int imageTest) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM4, imageTest);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
imageTest = getArguments().getInt(ARG_PARAM4);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
ImageView16by9 image = (ImageView16by9) view.findViewById(R.id.IVSlide);
image.setImageResource(imageTest);
return view;
}
}
ViewPager Adapter :
public class VPImageSliderAdapter extends FragmentStatePagerAdapter {
private int[] slides = {};
public VPImageSliderAdapter(FragmentManager fm){
super(fm);
}
public void addSlide(int drawable){
slides = Arrays.copyOf(slides,slides.length+1);
slides[slides.length-1]=drawable;
}
#Override
public int getCount() {
return slides.length;
}
#Override
public Fragment getItem(int position) {
return ViewPagerFragment.newInstance(slides[position]);
}
}
Change
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
to
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getChildFragmentManager());
it will work
Just needed to add :
ViewPager.setOffscreenPageLimit(5);
Related
Hello friends im developing android app with fragments in a viewpager but now i want to parse JSON data into the fragment.my question is how can i set number of fragments as the size of json data and insert the json data into the required fragment.please help me ive been searching for it on internet for hours but disappointment results so please help me.Thanks in advance!.
[{"c_id":13,"category_name":"PUBLICATIONS","imagename":"http://goringr.com/church_project/churchimagesnew/publications.jpg","ctype":"church"},{"c_id":14,"category_name":"YOUTH ASSOCIATION","imagename":"http://goringr.com/church_project/churchimagesnew/youthassociation.jpg","ctype":"church"}]
this is my json data and all i want is to display contents of object with c_id=13 in first fragment and display contents of object with c_id=14 in second fragment.
MainActivity.java
package project1.test;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static final String data = "hello";
FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toolbar tool = (Toolbar)findViewById(R.id.tool);
// setSupportActionBar(tool);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragment.newInstance(0, "Fragment1");
case 1:
return FirstFragment.newInstance(1, "Fragment2");
case 2:
return SecondFragment.newInstance(2, "Fragment3");
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
}
FirstFragment
public class FirstFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static FirstFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
;
View view = inflater.inflate(R.layout.fragment_first, container, false);
// TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
//// tvLabel.setText(page + " -- " + title);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)view.findViewById(R.id.collapsing_toolbar1);
collapsingToolbarLayout.setTitle("black panther");
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.sample_actions, menu);
}
}
SecondFragment
public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
Button tryit;
// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
SecondFragment fragmentSecond = new SecondFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentSecond.setArguments(args);
return fragmentSecond;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container,
false);
tryit = (Button) view.findViewById(R.id.tryit);
tryit.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),ManagingProfile.class);
startActivity(intent);
}
});
// TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
// tvLabel.setText(page + " -- " + title);
return view;
}
}
you can parse like this:
List<RidesData> ridesDatas; /* this is should be parcelable */
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FragmentAbout.newInstance(ridesDatas), "ABOUT");
adapter.addFragment(FragmentPointOfInterest.newInstance(ridesDatas),"POI");
viewPager.setAdapter(adapter);
}
and set constructure to each fragment like this:
FragmentAbout.class
public static FragmentAbout newInstance(List<RidesData> ridesDatas) {
FragmentAbout fragmentAbout = new FragmentAbout();
Bundle arg = new Bundle();
arg.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) ridesDatas);
fragmentAbout.setArguments(arg);
return fragmentAbout;
}
FragmentPointOfInterest.class
public static FragmentPointOfInterest newInstance(List<RidesData> ridesDatas) {
FragmentPointOfInterest fragmentPointOfInterest = new FragmentPointOfInterest();
Bundle arg = new Bundle();
arg.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) ridesDatas);
fragmentPointOfInterest.setArguments(arg);
return fragmentPointOfInterest;
}
and get each data of json in onViewCreated() method of fragment like this:
you have 2 position of data in json.
[0] = c_id=13
[1] = c_id=14
so in first fragment set 0 position:
RidesData data = ridesData.get(0);
and in second Fragment set 1 postion:
RidesData data = ridesData.get(1);
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ridesData = new ArrayList<>();
ridesData = getArguments().getParcelableArrayList("data");
RidesData data = ridesData.get(1);
}
You have to make use of custom adapter to extract the json data and view holder to print the data.
refer this link
The idea: In my app, it has 15 lessons, each lesson containing 30 couplets a user can swipe through. And each fragment/couplet_page has inflated a layout that contains 3 text views. I'm using FragmentStatePagerAdapter.
I've learned that use switch case statements to create swipe views but the problem is, there are lots of fragments to be created and I know that there is a better solution for it that I don't know. I just wanna use one fragment and somehow change the text with setText method.
here's my one fragment object code
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CoupletOneFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.couplet_one, container, false);
}
}
and here's the custom pager adapter
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class MyFragmentAdapter extends FragmentStatePagerAdapter {
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CoupletOneFragment();
case 1:
return new CoupletTwoFragment();
case 2:
return new CoupletThreeFragment();
case 3:
return new CoupletFourFragment();
case 4:
return new CoupletFiveFragment();
and so on...
default:
break;
}
return null;
}
#Override
public int getCount() {return 30;}
}
Try this way, in your state pager adapter use loop- size is number of fragments:
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
for (int i=0;i<size;i++){
adapter.addFragment(CoupletFiveFragment.newInstance(i));
}
viewPager.setAdapter(adapter);
Adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
}
Now your Fragment:
public static CoupletFiveFragment newInstance(int j) {
CoupletFiveFragment fragmentDemo = new CoupletFiveFragment();
Bundle args = new Bundle();
args.putInt("GET_LIST", j);
fragmentDemo.setArguments(args);
return fragmentDemo;
}
Get Value in Oncreate:
Int getINT=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getINT = getArguments().getInt("GET_LIST");
}
Well I'm gonna answer my own question here
Updated fragment object code
public class FragmentChild extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// INFLATE THE LAYOUT THAT EACH FRAGMENT OBJECT WILL HAVE, PUT IT IN A VIEW
View root = inflater.inflate(R.layout.couplets, container, false);
// RECEIVE THE BUNDLE DATA SENT (ARGUMENTS)
Bundle args = getArguments();
// CREATE AN ARRAY LIST OF STRINGS THAT WILL HOLD TEXT
ArrayList<String> someText = new ArrayList<>();
someText.add("one");
someText.add("two");
someText.add("three");
TextView txt = (TextView) root.findViewById(R.id.text_view);
txt.setText(someText.get(args.getInt("position")));
return root;
}
Updated custom pager adapter
class MyFragmentAdapter extends FragmentStatePagerAdapter {
MyFragmentAdapter(FragmentManager fm) {super(fm);}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt("position", position);
Fragment fragment = new FragmentChild();
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
And finally host activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_one);
// FIND THE VIEWPAGER AND SET THE CUSTOM ADAPTER TO IT TO PROVIDE CHILD PAGES
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
}
It was easy peasy!
I am using material design tabs as follows :
Following is my MainActivity.class :
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("onPageSelected Called");
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
My ViewPagerAdapter is as follows :
public class ViewPagerAdapter extends FragmentPagerAdapter {
private static int count = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
}
return null;
}
#Override
public int getCount() {
return count;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0 :
return "Tab One";
case 1 :
return "Tab Two";
}
return null;
}
}
and here are my Fragments :
This is my first fragment name is FragmentOne :
public class FragmentOne extends Fragment {
private EditText editText;
private Button btnSendData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT ONE");
View view = inflater.inflate(R.layout.fragment_one,container,false);
editText = (EditText) view.findViewById(R.id.et_name);
btnSendData = (Button) view.findViewById(R.id.btn_send);
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTwo fragment = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("username",editText.getText().toString());
fragment.setArguments(bundle);
getFragmentManager.beginTransaction.replace(R.id.frag_second,fragment).commit();
}
});
return view;
}
}
and here is another fragment with name FragmentTwo :
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT TWO");
View view = inflater.inflate(R.layout.fragment_two,container,false);
Bundle bundle = getArguments();
if(bundle!= null)
{
String value = getArguments().getString("username");
}
return view;
}
#Override
public void onResume() {
super.onResume();
System.out.println("onResume gets called");
}
}
In the second fragment i am getting data buts its adding another view with previous one.
see the image :
so I want to pass data from FragmentOne to FragmentTwo in two scenario :
1. I want to pass the data when i click on button and
2. When I swipe to FragmentTwo data should be passed
Also when I try to swipe to FragmentTwo nothing gets called in FragmentTwo ? why is it so ?
Also when I click to second tab nothing gets called .
Please help me how should i pass data to FragmentTwo on button click ?
following are layout files:
here is fragment_one
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:id="#+id/et_name"
android:hint="Username"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:padding="16dp"
android:text="Send Data"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:id="#+id/btn_send"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
and second fragment , fragment_second.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/second_frag"
android:gravity="center">
<TextView
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fragment Two"
android:id="#+id/textView2" />
Each fragment is associated with the parent activity. so you can't directly communicate from one fragment to another fragment. You will need to go through Parent Activity using interface.
Check this docs : https://developer.android.com/training/basics/fragments/communicating.html
On button click pass the value to methods in your custom interface and access those methods in second fragment.
when I try to swipe to FragmentTwo nothing gets called in FragmentTwo
For this you need to implement fragment life cycle - https://developer.android.com/reference/android/app/Fragment.html
UPDATE
Done with some modification in you code, just look at the foll. code -
Manifex.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java
package com.app.onkar.tabdemo;
import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "ONE");
adapter.addFragment(new FragmentTwo(), "TWO");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("onPageSelected Called");
}
#Override
public void onPageScrollStateChanged(int state) {
}
public static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private static int count = 2;
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
}
return null;
}
#Override
public int getCount() {
return count;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab One";
case 1:
return "Tab Two";
}
return null;
}
}
}
FragmentOne.java
package com.app.onkar.tabdemo;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentOne extends Fragment {
private EditText editText;
private Button btnSendData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT ONE");
View view = inflater.inflate(R.layout.fragment_one,container,false);
editText = (EditText) view.findViewById(R.id.et_name);
btnSendData = (Button) view.findViewById(R.id.btn_send);
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTwo fragment = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("username",editText.getText().toString());
fragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
}
});
return view;
}
}
FragmentTwo.java
package com.app.onkar.tabdemo;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT TWO");
View view = inflater.inflate(R.layout.fragment_two,container,false);
TextView txt2 = (TextView) view.findViewById(R.id.textView2);
Bundle bundle = getArguments();
if(bundle!= null)
{
String value = getArguments().getString("username");
txt2.setText(value);
}
return view;
}
#Override
public void onResume() {
super.onResume();
System.out.println("onResume gets called");
}
}
No change in Layout files. Just try above code - it is working exactly as you want. Hope it will help!
SCREENS
ViewPagerAdapter class
public class ViewPagerAdapter extends FragmentPagerAdapter {
private static int count = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment fragmentone = new FragmentOne();
Bundle args = new Bundle();
args.putInt("code", 1);
fragmentone.setArguments(args);
return fragmentone;
break;
case 1:
Fragment fragmenttwo = new FragmentTwo();
Bundle args = new Bundle();
args.putInt("code", 2);
fragmenttwo.setArguments(args);
return fragmenttwo ;
break;
}
return null;
}
#Override
public int getCount() {
return count;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0 :
return "Tab One";
case 1 :
return "Tab Two";
}
return null;
}
}
args is the bundle object, you can put String int and other values to use these values in fragment use below code in onCreateView method of Fragment.
int codeForthisFragment = getArguments().getInt("code");
for button click:
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment secondFragment = new FragmentTwo();
Bundle args = new Bundle();
args.putInt("code", 2);
secondFragment.setArguments(args);
ft.replace(R.id.content_frame, secondFragment);
ft.commit();
In the second fragment i am getting data buts its adding another view with previous one. see the image
With reference to the answer by #Roy Miller(https://stackoverflow.com/users/5255021/roy-miller),
you can solve it by doing the follwing changes:
In MainActivity.java ,replace the follwing switch:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
}
return null;
}
With:
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return mFragmentList.get(0);
case 1:
return mFragmentList.get(1);
case 2:
return mFragmentList.get(2);
default:
return null;
}
}
And then, in FragmentOne.java
Replace this:
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTwo fragment = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("username",editText.getText().toString());
fragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
}
});
With:
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*This one FragmentCollection is a Singleton class that contains list of fragments, set it during initialization itself(code is attached below this code)*/
FragmentCollection fragmentCollection=FragmentCollection.getInstance();
FragmentTwo fragment = (FragmentTwo) FragmentCollection.getmFragmentList().get(2); //getting the second fragment
fragment.setText(editText.getText().toString()); //add this method in fragment two
}
});
Now inside FragmentTwo.java
Add the method:
public void updateTextView(String data){
Log.d("TabTwo","Update Text view");
TextView txt = (TextView)view.findViewById(R.id.textView2);
txt.setText(data);
}
At last, the singleton class i mentioned above:
public class FragmentCollection {
static FragmentCollection fragmentCollection=new FragmentCollection();
private final List<Fragment> mFragmentList = new ArrayList<>();
private FragmentCollection(){}
public static FragmentCollection getInstance(){
if(fragmentCollection!=null) {
return fragmentCollection;
}else {
return new FragmentCollection();
}
}
public void setmFragmentList(List<Fragment> mFragmentList){
this.mFragmentList.addAll(mFragmentList);
}
public List<Fragment> getmFragmentList(){
return mFragmentList;
}
}
The issue of getting older views overlapping is because of initializing the fragment again and again
like new FragmentTwo(); in more than one place.
So here we put it in a list and access it so only a single fragment is altered.
I am not able to go to first fragment from Second fragment . I am using tab layout
This is my code
By clicking button from 2nd Fragment
Bundle bundle = new Bundle();
bundle.putString("uniqueList1", uniqueList.get(0));
bundle.putString("uniqueList2", uniqueList.get(1));
bundle.putString("kycUniquesNo", kycUniqueNum);
CustBasicFormFragement fragObj = new CustBasicFormFragement();
fragObj.setArguments(bundle);
In 1st Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
binding = DataBindingUtil.inflate(inflater, R.layout.cust_basic_form_fragment, container, false);
view = binding.getRoot();
if (getArguments() != null) {
string1 = getArguments().getString("uniqueList1");
string2 = getArguments().getString("uniqueList2");
kycUnique=getArguments().getString("kycUniquesNo");
System.out.print(string1);
System.out.print(string2);
System.out.print(kycUnique);
return view;
}
In my app I want to use swipe views of four tabs inside a fragment. The four tabs are contains different fragments each and all the four fragments are sliding by swipe from right to left or vice versa. The fragments are working fine but the tabs are not visible within the fragment. Anyone have any solution for this. Thanks in advance :)
this is the main fragment which contains the tabs:-
public class DashboardTabFragment extends Fragment implements ActionBar.TabListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
private ViewPager viewPager;
public DashboardTabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
setHasOptionsMenu(true);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
TabPageAdapter tabPageAdapter = new TabPageAdapter(getActivity().getSupportFragmentManager(), getActivity());
viewPager.setAdapter(tabPageAdapter);
for (String aTabTitle : tabTitle)
actionBar.addTab(actionBar.newTab().setText(aTabTitle).setTabListener(this));
return rootView;
}
This is the adapter for fragments:-
public class TabPageAdapter extends FragmentPagerAdapter {
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
I found the solution. I used TabHost for tabs with viewpager.
This is my fragment :-
package com.itpp.trt;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
public class DashboardTabFragment extends Fragment implements ViewPager.OnPageChangeListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private ViewPager mViewPager;
private TabHost tabHost;
private String[] tabSpec = {"Tab_1", "Tab_2", "Tab_3", "Tab_4"};
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
private TabHost.TabContentFactory mFactory = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
View v = new View(getActivity());
v.setMinimumHeight(0);
return v;
}
};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
public DashboardTabFragment() {
tabHost = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
mViewPager.setAdapter(new TabPageAdapter(getChildFragmentManager(), getActivity()));
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup();
mViewPager.setOnPageChangeListener(this);
for (int i = 0; i < tabSpec.length; i++) {
tabHost.addTab(tabHost.newTabSpec(tabSpec[i]).setIndicator(tabTitle[i]).setContent(mFactory));
}
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equals("Tab_1")) {
mViewPager.setCurrentItem(0);
} else if (tabId.equals("Tab_2")) {
mViewPager.setCurrentItem(1);
} else if (tabId.equals("Tab_3")) {
mViewPager.setCurrentItem(2);
} else if (tabId.equals("Tab_4")) {
mViewPager.setCurrentItem(3);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is my tabpager adapter :-
package com.itpp.trt;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by biswajit on 28-11-14.
*/
public class TabPageAdapter extends FragmentStatePagerAdapter{
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Hope this helps other. Thanks :)
I'm trying to build a simple application that displays two fragments. The first fragment is displayed by default. It contains a list of names which you can choose and when you click on one of the items, it supposes to display a second fragment with a text view, displaying the name you have chosen.
The problem is everytime I click one of the names on the list, it throws me a NullPointerException. I really don't know what could be the problem.
Here are the codes( The app contains three class - two fragments and one activity. The FriendsF fragment is the list fragment and it performs well. The second fragment is FeedFragment and onitemclick it should display the name that was clicked)
FriendsF fragment:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FriendsF extends ListFragment {
private static final String[] FRIENDS = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public interface SelectionListener {
public void onItemSelected(int position);
}
private SelectionListener mCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), layout, FRIENDS));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (SelectionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SelectionListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (isInTwoPaneMode()) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
mCallback.onItemSelected(position);
}
private boolean isInTwoPaneMode() {
return getFragmentManager().findFragmentById(R.id.tweets) != null;
}
}
FeedFragment:
package com.example.fragmentsexcersize;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FeedFragment extends Fragment{
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public FeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
return rootView;
}
public void updateFeedDisplay(int position) {
mTextView.setText(data[position]);
}
}
MainActivity:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.app.FragmentTransaction;
public class MainActivity extends Activity implements FriendsF.SelectionListener{
private FriendsF mFriendsFragment;
private FeedFragment mFeedFragment;
private FragmentManager fragMana;
private FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFriendsFragment = new FriendsF();
fragMana = getFragmentManager();
transaction = fragMana.beginTransaction();
transaction.add(R.id.friends, mFriendsFragment);
transaction.commit();
}
private boolean isInTwoPaneMode() {
return findViewById(R.id.tweets) == null;
}
public void onItemSelected(int position) {
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
transaction = fragMana.beginTransaction();
transaction.add(R.id.tweets, mFeedFragment);
transaction.commit();
}
mFeedFragment.updateFeedDisplay(position);
}
}
Make the following changes to your source:
MainActivity
public void onItemSelected(int position) {
Bundle bundle = new Bundle();
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
bundle.putInt("POSITION", position);
mFeedFragment.setArguments(bundle);
transaction = fragMana.beginTransaction();
transaction.replace(R.id.tweets, mFeedFragment);
transaction.commit();
}
}
FeedFragment
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
int mPosition = getArguments().getInt("POSITION", 0);
mTextView.setText(data[mPosition]);
return rootView;
}