Using Fragments in View pager - android

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) {
}
});

Related

Progress bar update on Swiping fragments

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!

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 adapter in android

Why does my pager adapter doesn't want to start from my first item. When I start ContainerIspiti activity, and show first fragment, the view pager dones't show the right element. Insted of first, view pager shows the second element, and I can't to swipe to first element of my array list. Does anybody have solution.
Here is my code for ConainterIspiti
public class ContainerIspiti extends FragmentActivity{
private Button next, previous, odgovori, informacije;
private TextView textPitanja, brojPitanja;
private ViewPager pager;
private PagerAdapter mPagerAdapter;
public static ArrayList<Pitanja> getAllPitanja;
public static ArrayList<Pitanje_has_Slika> getAllImages;
private Intent intent;
private DBTools db = new DBTools(this);
private ProgressDialog pDialog;
private int broj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_container_pitanja);
Bundle bundle = new Bundle();
intent = getIntent();
Dohvati d = new Dohvati();
d.execute();
textPitanja = (TextView) findViewById(R.id.kategorijaTextViewPitanjeActivity);
brojPitanja = (TextView) findViewById(R.id.brojPitanjaTextViewPitanjeActivity);
pager = (ViewPager) findViewById(R.id.pagerPitanja);
pager.setCurrentItem(0, true);
bundle.putString("NAZIV_KATEGORIJE", intent.getStringExtra("NAZIV_KATEGORIJE"));
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.i("Position je sljedeci ", String.valueOf(position));
return PitanjaFragment.create(position);
}
#Override
public int getCount() {
Log.i("Velicina polja je ", String.valueOf(getAllPitanja.size()));
Log.i("Prvi eleemnt liste je", getAllPitanja.get(0).getTextPitanja());
return getAllPitanja.size();
}
}
private class Dohvati extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContainerIspiti.this);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
getAllPitanja = db
.getAllPitanja(intent.getStringExtra("id_kategorije"));
Log.i("Ovoliki je get all pitanja", String.valueOf(getAllPitanja.size()));
getAllImages = db.getAllPitanjaImages();
Log.i("ovoliko je slika", String.valueOf(getAllImages.size()));
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
brojPitanja.setText(String.valueOf(position) + "/" + String.valueOf(getAllPitanja.size()));
broj = position;
}
});
textPitanja.setText(intent.getStringExtra("NAZIV_KATEGORIJE"));
brojPitanja.setText(String.valueOf(broj) + "/" + getAllPitanja.size());
}
}
}
and here is my fragment activity
public class PitanjaFragment extends Fragment implements API{
public static final String ARG_PAGE = "page";
private int broj;
private ImageView image;
private TextView textPitanja;
private String uri;
private View view;
private ListView listView;
private Typeface custom_font;
private boolean odgovoreno, tocno;
private ArrayList<Odgovor> odgovorList;
private PitanjaAdapter adapter;
private DBTools db;
private List<Integer> kliknuti;
private HashMap<Integer, List<Integer>> odgBrojPitanja;
public static PitanjaFragment create(int pageNumber) {
PitanjaFragment fragment = new PitanjaFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public PitanjaFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broj = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_pitanja, container, false);
image = (ImageView) view.findViewById(R.id.imageSlikaImageView);
image.setOnClickListener(this);
textPitanja = (TextView) view.findViewById(R.id.textPitanjaTextViewPitanjaActivity);
db = new DBTools(getActivity());
listView = (ListView) view.findViewById(R.id.listView);
updateDisplay((broj+1));
return view;
}
public void updateDisplay(int z) {
odgovoreno = false;
tocno = true;
textPitanja.setText(stripHtml(String.valueOf(ContainerIspiti.getAllPitanja.get(z).getTextPitanja())));
image.setImageBitmap(null);
//info = ContainerIspiti.getAllPitanja.get(z).getInfo();
Log.d("Postoji", ContainerIspiti.getAllImages.get(z).getNazivSlike() + ", ");
for (int j = 0; j < ContainerIspiti.getAllImages.size(); j++) {
if (ContainerIspiti.getAllImages.get(j).getIdPitanja() == ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
&& ContainerIspiti.getAllImages.get(j).getNazivSlike() != null) {
Log.i("Id pitanja slike + idpitanja pitanja + idSlike",
ContainerIspiti.getAllImages.get(j).getIdPitanja()
+ ", "
+ String.valueOf(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
+ ", "
+ ContainerIspiti.getAllImages.get(j).getIdSlika()));
image.setVisibility(View.VISIBLE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi);
//povecalo.setEnabled(true);
uri = PregledZnakova.PHOTOS_BASE_URL
+ ContainerIspiti.getAllImages.get(j).getNazivSlike();
int rounded_value = 40;
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.placeholder).showStubImage(R.drawable.placeholder).cacheInMemory().cacheOnDisc().displayer(new RoundedBitmapDisplayer(rounded_value)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(uri, image,options);
break;
// }
} else {
image.setVisibility(View.GONE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi_neaktivno);
//povecalo.setEnabled(false);
}
}
odgovorList = db.getAllOdgovore(Integer.toString(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()));
adapter = new PitanjaAdapter(getActivity(),
R.layout.pitanja_entry, odgovorList);
listView.setAdapter(adapter);
for (int i=0;i<ContainerIspiti.getAllPitanja.size();i++){
if (ContainerIspiti.getAllPitanja.get(i).isTocno()){
Log.i("Ovo pitanje je tocno", ContainerIspiti.getAllPitanja.get(i).getTextPitanja());
}
}
}
#Override
public int getItemBroj() {
return broj;
}
#Override
public int getPosition() {
return broj;
}
#Override
public void setPosition(int position) {
this.broj = position;
}
#Override
public Fragment getFragment() {
return this;
}
}
Thanks for your time and your help.
In the onCreateView() method of your PitanjaFragment class, replace:
updateDisplay((broj+1));
with
updateDisplay(broj);
Try this. It should work.

Categories

Resources