Progress bar update on Swiping fragments - android

Im creating an application to show data in progress bar based on the selected fragment , so if particular fragment is selected the progress bar should show the data in that fragment and so on , in my application there are three fragments the data in progress bar gets updated for two fragments and not working for the third one ,ive tried with log everything looks fine ,,Ive tried giving logs and what ive figued out is that the fragment that is being opened is only two of them and im not getting the third log , even when i open the third fragment,and im getting an indication of opening the third fragment if i again move back to the second fragment,i cant figure out where im missing it . below is my code
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES =3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Paint progressPaint = new Paint();
private int lineHeight = 30;
private Paint incompletePaint = new Paint();
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
new Progress(0).execute();
new Progress2(0).execute();
new Progress3(0).execute();
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(R.id.pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 3; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage); //set the current page
return v;
// return inflater.inflate(R.layout.fragment_history, container, false);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
int i = 0;
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
Log.e("Fragment","Fragment 1::"+String.valueOf(i));
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
return SlideFragment.newInstance(String.valueOf(0), " ");
case 1: // Fragment # 1 - This will show SecondFragment
Log.e("Fragment","Fragment 2");
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
return Slidetwo.newInstance(String.valueOf(1), " ");
case 2: // Fragment # 1 - This will show SecondFragment
Log.e("Fragment","Fragment 3");
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(0).execute();
return SlideThree.newInstance(String.valueOf(2), " ");
default:
return null;
}
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 1;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
// Progress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#C0D000"), android.graphics.PorterDuff.Mode.SRC_ATOP);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer> {
int dummyVariable = 0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
// TODO: Rename method, update argument and hook method into UI event
}

Did you set offscreenPaginglimit?
Try setting
yourViewPager.setOffScreenPagingLimt=2;
Let me know if this helps out!

Related

Using Fragments in View pager

I am Creating an application which uses different fragments inside a view pager , there are three progress bars on the left of view pager in which the data changes in according to the fragments ,But when i run the application all data assigned to the progress bars are getting displayed , without swiping the fragments and while swiping the fragments the data is not changed in the progress bars, here is my code
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES = 3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Paint progressPaint = new Paint();
private int lineHeight = 30;
private Paint incompletePaint = new Paint();
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(R.id.pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 3; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage);//set the current page
mPager.setOffscreenPageLimit(4);
return v;
// return inflater.inflate(R.layout.fragment_history, container, false);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
int i = 0;
#Override
public Fragment getItem(int position)
{
if(position==0){
Log.e("Fragment","Fragment 1::"+String.valueOf(i));
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
return SlideFragment.newInstance(0, " ");}
if(position==1){
Log.e("Fragment","Fragment 2");
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
return Slidetwo.newInstance(String.valueOf(0), " ");}
if (position==2)
Log.e("Fragment","Fragment 3");
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(40).execute();
return SlideThree.newInstance(String.valueOf(0), " ");
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
Don't change the progress in pager adapter. for that add below code and in the onPageSelected() method based on the position change the progress.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Progress bars and Fragments

Im trying to update the progress bar based on the swiping of fragments , totally there are three fragments , and three circular progress bar , im getting the progress bar along with the test values no problem about that , but im not getting the fragments displayed ,this is the code please let me know where im wrong .
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES = 3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Log.e("History ", String.valueOf(page));
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
Log.e("History2 ", param1+param2);
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(30).execute();
/* new Progress(0).execute();
new Progress2(0).execute();
new Progress3(0).execute();*/
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager()) {
#Override
public int getCount()
{
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
};
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage);
mPager.setOffscreenPageLimit(0);
//set the current page
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position)
{
// Check if this is the page you want.
getItem(position);
Log.e("Started","hello");
}
public Fragment getItem(int position) {
int i = 0;
switch (position) {
case 0: { // Fragment # 0 - This will show FirstFragment
if (!(i < 3)) {
}
++i;
return SlideFragment.newInstance(String.valueOf(0), " ");
}
case 1: { // Fragment # 1 - This will show SecondFragment
Log.e("Fragment", "Fragment 2");
if (!(i < 3)) {
/*new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();*/
}
++i;
return Slidetwo.newInstance(String.valueOf(1), " ");
}
case 2: { // Fragment # 1 - This will show SecondFragment
Log.e("Fragment", "Fragment 3");
if (!(i < 3)) {
/* new Progress(50).execute();
new Progress2(10).execute();
new Progress3(0).execute();*/
}
++i;
return SlideThree.newInstance(String.valueOf(2), " ");
}
default:
return null;
}
}
});
return v;
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
// Progress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#C0D000"), android.graphics.PorterDuff.Mode.SRC_ATOP);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer> {
int dummyVariable =0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable =0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
private class ScreenSlidePagerAdapter extends PagerAdapter {
public ScreenSlidePagerAdapter(Object fragmentManager) {
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
// TODO: Rename method, update argument and hook method into UI event
}
`

Call method inside a fragment

PageAdapter:
class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
private int PAGE_COUNT = 3;
private String tabTitles[];
public SampleFragmentPagerAdapter(FragmentManager fm, String[] categorie) {
super(fm);
PAGE_COUNT = categorie.length;
tabTitles = new String[categorie.length];
for(int i = 0; i < categorie.length; i++){
tabTitles[i] = categorie[i];
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
return Pagina.newInstance(position + 1);
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
fragment activity :
public class Pagina extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
public static Pagina newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Pagina fragment = new Pagina();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
// Inflate the fragment layout we defined above for this fragment
// Set the associated text for the title
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pagina, container, false);
//TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
//tvTitle.setText("Fragment #" + mPage);
Log.e("STATO", "CI SIAMOOO");
return view;
}
public void getSecondScrollView(String str){
Log.e("ECCOLOO", "AVVIATO");
}
}
mainActivity :
public class PrincipaleActivity extends FragmentActivity{
public String[] categorie;
private String linguaApp = Locale.getDefault().getLanguage();
private Boolean linguaPresente = false;
private float scale;
private NetworkImageView imgProdotto;
private ViewPager pager;
private PagerSlidingTabStrip tabs;
private int screenWidth;
private int screenHeight;
private JSONObject dati;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principale);
Intent intent = getIntent();
try {
dati = new JSONObject(intent.getStringExtra("DatiArticolo"));
checkLingua();
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERRORE", "Errore durante il parsing del JSONObject o del checkLingua");
}
((myMainScrollView)findViewById(R.id.scrollPrincipale)).setScrollingEnabled(false);
creaCategorie();
caricaImgProdotto();
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),categorie));
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
setDimensioniSchermo();
inizializzaPagina();
}
private void creaCategorie(){
categorie = new String[dati.optJSONArray("categorie").length()];
for (int h = 0; h < dati.optJSONArray("categorie").length(); h++){
try {
JSONObject temp = (JSONObject) dati.optJSONArray("categorie").get(h);
categorie[h] = temp.optJSONObject("nome").optString(linguaApp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void caricaImgProdotto(){
imgProdotto = (NetworkImageView) findViewById(R.id.imgProdotto);
String url = "http://46.101.209.16/"+dati.optJSONObject("anagrafica").optJSONObject(linguaApp).optJSONObject("img").optString("path");
Log.e("LINK IMG", url);
ImageLoader imageLoader = MyImageLoader.getInstance(this.getApplicationContext()).getImageLoader();
imageLoader.get(url, ImageLoader.getImageListener(imgProdotto, R.drawable.icona_flash, android.R.drawable .ic_dialog_alert));
imgProdotto.setImageUrl(url, imageLoader);
}
private void checkLingua() throws JSONException {
JSONArray valLingue = dati.optJSONObject("lingue").optJSONArray("lingueApp");
for(int i = 0; i < valLingue.length(); i++){
if(valLingue.get(i).equals(linguaApp)){
linguaPresente = true;
}
}
if (linguaPresente == false){
linguaApp = dati.optJSONObject("lingue").optString("principale");
}
Log.e("Lingua Scelta ",linguaApp);
}
private void setDimensioniSchermo(){
scale = getResources().getDisplayMetrics().density;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}
private void inizializzaPagina(){
imgProdotto.getLayoutParams().height = (screenWidth/3)*2;
tabs.getLayoutParams().height = (int)(scale * 30);
pager.getLayoutParams().height = screenHeight - (int)(scale * 30);
}
}
how can i call the method getSecondScrollView from my SampleFragmentPagerAdapter ?
i'm using this : https://github.com/jpardogo/PagerSlidingTabStrip
i need the methods inside the fragment for get outside some views
sorry for bad english, i'm italian :D
use this code in activity that have access to ViewPager :
Pagina fragment = (Pagina ) getSupportFragmentManager()
.findFragmentByTag( makeFragmentName(pager.getId(),page_index_of_pagina_fragment_inViewPager));
then call fragment.getSecondScrollView("str");
and this is makeFragmentName method that gets fragment name from adapter:
private String makeFragmentName(int viewPagerId, int index) {
return "android:switcher:" + viewPagerId + ":" + index;
}
note calls must be done after fragment completely loaded
Try using a callbacklistener, make Pagina implement an interface for example PagerAdapterListener which has the method onGetSecondScrollView(), like this:
public interface PagerAdapterListener {
void onGetSecondScrollView(String str);
}
Then add a PagerAdapterListener to your Adapter's constructor, so that your Adapter has a variable of the type PagerAdapterListener (new SampleFragmentPagerAdapter(..., ..., this)) . When you need to call the getSecondScrollView() method just call the onGetSecondScrollView() method on the interface (which is actually your Fragment).
And ofcourse dont forget to implement the PagerAdapterListener and its onGetSecondScrollView() method like this:
public class Pagina extends Fragment implements PagerAdapterListener {
#Override
public void onGetSecondScrollView(String str) {
getSecondScrollView(str);
}
}

How does findFragmentByTag work in a parent Fragment to know which child fragment is currently showing with ViewPagerAdapter?

My MainFragment is like
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(3);
// changeTab();
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
pager.setCurrentItem(position_tab);
}
Log.e("Fragment", fragment + "" +pager.getCurrentItem());
//
return view;
}
public void changeTab(){
pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss" ,(Fragment) maps.get(position).get(KEY_FRAGMENT) +"");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
#Override
public int getCount() {
return maps.size();
}
}
}
Here I can get that this fragment is visible by using findFragmentByTag. I wanna know how I can use same thing for the child of this Fragment which are added using FragmentPagerAdapter.
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
Log.e("Fragment", fragment + "" +pager.getCurrentItem()); }
So now I wanna do same thing and get name of current selected Fragment out of 3 which are mentioned above in FragmentPagerAdapter as AdvisoryPagerFragment,TopAdvisoryPagerFragment and ExperViewPagerFragment.
Try this
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if(fragment instanceOf Fragment1){
// Do something
}else if(fragment instanceOf Fragment2){
// Do something
}else{
// Do something
}

viewpager with images works but on back button images don't show

I have a viewpager with image fragments in it that works but on back was getting an error saying that there is no empty constructor. I made one but now my images don't show up because imageResourceId is null. I've tried a million things and can't figure it out.
public final class TestFragment extends Fragment {
String imageResourceId;
public TestFragment() {
}
public TestFragment(String cONTENT) {
imageResourceId = cONTENT;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
new DownloadImageTask((ImageView) image).execute(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
class TestFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public String[] CONTENT;
private int mCount;
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar, R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms, R.drawable.perm_group_location };
public TestFragmentAdapter(FragmentManager fm, JSONArray photoData) {
super(fm);
// photoData = (JSONArray) userProfile.get("photos");
CONTENT = new String[photoData.length()];
mCount = photoData.length();
for (int i = 0; i < photoData.length(); i++) {
JSONObject mainPhoto;
try {
mainPhoto = photoData.getJSONObject(i);
CONTENT[i] = mainPhoto.getString("src_big");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
return new TestFragment(CONTENT[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
in the activity
mAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), photoData);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (LinePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
Android uses the empty constructor of a fragment to restore the fragment when there is a configuration change, that's why you can't modify it, and you can't override it because you get an error in eclipse. The best practice to pass arguments to a fragment, when instantiating it, is to use an static factory method:
public class TestFragment extends Fragment {
String imageResourceId;
public static TestFragment newInstance(String resource) {
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("Resource", resource);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResourceId = getArguments().getString("Resource");
}
}
To instanciate it you use the static method:
TestFragment fragment = TestFragment.newInstance("some string");

Categories

Resources