ViewPager with the dots only beginning on the third slide (3/3) - android

I've a ViewPager, with dots, and it's only beginning on the third slide [3/3].
But sometimes, the second slide is not showed in the ViewPager. I tried to use the Log, to show the initial position and the current position, when the position changes, and the result was: the second option is not showed, only the first and the third.
The resume of the hierarchy of my class is:
HelpHomeFragment extends BaseFragment {
ViewPagerAdapter extends PagerAdapter {}
HelpFrag1 extends Fragment {}
HelpFrag2 extends Fragment {}
HelpFrag3 extends Fragment {}
}
and my code is below:
HelpHomeFragment.java
public class HelpHomeFragment extends BaseFragment {
#BindView(R.id.llt_help_tipsbase)
LinearLayout llTips;
#BindView(R.id.vpg_help)
ViewPager viewPager;
#BindView(R.id.slider_dots)
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
private static final String ARG_PARAM1 = "Title";
private DataManager dm;
private HelpHomeFragmentPresenter<HelpHomeFragment> presenter;
private ListHelpsAdapter listHelpsAdapter;
private MyTimerTask mtt;
public static Fragment newInstance(String title) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, title);
Fragment fragment = new HelpHomeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dm = ((MvpApp) getActivity().getApplication()).getDataManager();
presenter = new HelpHomeFragmentPresenter<>(dm);
presenter.onAttach(this);
}
#Override
public void onResume() {
super.onResume();
showSlideshowTips();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_help_home, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void showSlideshowTips() {
configSlideshow();
}
#Override
public void configSlideshow() {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotscount; i++)
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
dots[position].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
try {
mtt = new MyTimerTask();
new Timer().scheduleAtFixedRate(mtt, 4500, 9000);
} catch (Exception e) {
e.printStackTrace();
}
}
// CUSTOM TIMER
class MyTimerTask extends TimerTask {
#Override
public void run() {
try {
getBaseActivity().runOnUiThread(() -> {
if (viewPager.getCurrentItem() == 0) {
viewPager.setCurrentItem(1);
} else if (viewPager.getCurrentItem() == 1) {
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
// CUSTOM PAGE ADAPTER
class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Fragment[] fragments = {new HelpFrag1(), new HelpFrag2(), new HelpFrag3()};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = null;
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.custom_layout, null);
try {
View finalView = view;
getActivity().runOnUiThread(() -> getActivity().getSupportFragmentManager().beginTransaction()
.replace(finalView.getId(), fragments[position], "findThisFragment")
.addToBackStack(null).commit());
} catch (Exception e){
e.printStackTrace();
}
}
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
// classes fragment for the slideshow. Each fragment is an slide
public static class HelpFrag1 extends Fragment {
public HelpFrag1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_help_frag1, container, false);
}
}
// and more two classes HelpFrag, only changing the end (HelpFrag2 and HelpFrag3)
// and changing the layout to fragment_help_frag2 and fragment_help_frag3
}
and my layout base of the ViewPager is:
fragment_help_home.xml
<!-- another tag -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vpg_help"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:paddingTop="4dp"
android:layout_marginRight="30dp"
android:overScrollMode="never" />
<LinearLayout
android:id="#+id/slider_dots"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="-20dp"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal" />
</LinearLayout>
<!-- another tag -->

Related

how to slide images automatically along by sliding custom by fingers

I have implemented an image slider with dots. Working perfectly. Slider is working only on manual by sliding from finger left or right not automatically by a time interval 3 seconds.
See the code and suggest me some approach to working slider automatically.
ViewPager in .xml layout file
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_alignParentTop="true" />
<LinearLayout
android:paddingTop="8dp"
android:id="#+id/slider_dots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal|center_vertical"
android:layout_below="#id/view_pager"></LinearLayout>
</RelativeLayout>
And here's ViewPageAdapter java class
public class ViewPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
int images[] = {R.mipmap.banner, R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner3, R.mipmap.banner4, R.mipmap.banner5};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slider_banner_layout, null);
ImageView imageView = view.findViewById(R.id.image_view_banner_image);
imageView.setImageResource(images[position]);
ViewPager viewPager = (ViewPager) container;
viewPager.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager viewPager = (ViewPager) container;
View view = (View) object;
viewPager.removeView(view);
}
}
MainActivity.java
public class HomeActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout sliderDotsPanel;
ImageView[] dots;
private int dotCount;
ViewPagerAdapter viewPagerAdapter;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.app_bar);
toolbar.setTitle("");
toolbar.setLogo(R.mipmap.toolbar_logo);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
viewPagerAdapter= new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
sliderDotsPanel=findViewById(R.id.slider_dots);
initializeDots();
}
private void initializeDots() {
dotCount = viewPagerAdapter.getCount();
dots = new ImageView[dotCount];
for (int i = 0; i < dotCount; i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotsPanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotCount; i++) {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
I will show you how to make it slide, one page after the other and then stop:
private void slideAutomatically(final long milliSeconds){
new Thread(new Runnable(){
#Override
public void run(){
for(int i = 0 ; i<6 ; i++){
//sleep
try{
Thread.sleep(milliSeconds);
}catch(InterruptedException e){
}
//change position
runOnUiThread(new Runnable(){
#Override
public void run(){
viewPager.setCurrentItem(i);}
});
}
}
}).start();
}
Call this method whenever you want the pages to slide automatically:
//lets say I want the pages to change every 3 seconds
slideAutomatically(3000);

Fragment must be a public static class to be properly recreated from instance state?

After updating to the support repository,
compile('com.android.support:support-v4:26.+') {
force = true
}
compile('com.android.support:appcompat-v7:26.+') {
force = true
}
compile('com.android.support:design:26.+') {
force = true
}
compile('com.android.support:cardview-v7:26.+') {
force = true
}
compile('com.android.support:recyclerview-v7:26.+') {
force = true
}
I'm getting this weird exception.
TransactionDetailsFragment must be a public static class to be properly recreated from instance state
Here is a my source code
public class TransactionDetailsViewFragment extends MainFragment implements FragmentWithKeepPrevious, FragmentWithName, FragmentWithBackAction {
private ViewPager mViewPager;
private PagerTitleStrip mPagerTitleStrip;
private View mView;
private int transaclionPosition;
private List<Transaction> cashTransactions;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_transaction_details_view, container, false);
mViewPager = mView.findViewById(R.id.u_transaction_details_viewpager_3);
mPagerTitleStrip = mView.findViewById(R.id.u_transaction_details_header);
try {
cashTransactions = new ArrayList<>();
if (GlobalClassParameters.transactions != null) {
cashTransactions = GlobalClassParameters.transactions;
}
} catch (ClassCastException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
if (cashTransactions != null)
mViewPager.setAdapter(new ScreenSlidePagerAdapter(getChildFragmentManager()));
mPagerTitleStrip.setTextColor(Color.parseColor("#ffffff"));
Bundle bundle = this.getArguments();
if (bundle != null) {
transaclionPosition = bundle.getInt("transactionPosition");
mViewPager.setCurrentItem(transaclionPosition);
}
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
try {
mViewPager.setCurrentItem(position);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return mView;
}
void syncTitles() {
for (int counter = 0; counter < mPagerTitleStrip.getChildCount(); counter++) {
if (mPagerTitleStrip.getChildAt(counter) instanceof TextView) {
TextView textView = ((TextView) mPagerTitleStrip.getChildAt(counter));
UniPAYTypefaceUtils.setLocalisation(textView, getActivity(), TextStyle.LIGHT);
textView.setTextSize(14);
}
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
TransactionDetailsFragment transactionDetailsFragment = new TransactionDetailsFragment();
transactionDetailsFragment.setTransaction(cashTransactions.get(position).getTransactionDetails().getTransactionView());
transactionDetailsFragment.setTransactionButtons(cashTransactions.get(position).getTransactionDetails().getTransationButton());
transactionDetailsFragment.setmTransactionPosition(position);
syncTitles();
return transactionDetailsFragment;
}
#Override
public int getCount() {
return cashTransactions.size();
}
#Override
public CharSequence getPageTitle(int position) {
String title = cashTransactions.get(position).getName();
SpannableString whiteSpannable = new SpannableString(title);
return whiteSpannable;
}
}
#Override
public boolean onBack() {
transaclionPosition = 0;
return true;
}
#Override
public int getName() {
return R.string.u_transaction_details;
}
#Override
public Class getBackFragment() {
transaclionPosition = 0;
return HistoryFragment.class;
}
public class TransactionDetailsFragment extends Fragment {
private List<KeyValueParams> mTransaction;
private List<TransationButton> transationButtons;
private int mTransactionPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.view_transaction_details, container, false);
CustomRecyclerView listView = view.findViewById(R.id.u_transaction_details);
if (mTransaction != null) {
final KeyValueRecyclerViewAdapter keyValueAdapter = new KeyValueRecyclerViewAdapter(getActivity(), mTransaction);
listView.setAdapter(keyValueAdapter);
listView.setLayoutManager(new LinearLayoutManager(getActivity()));
keyValueAdapter.notifyDataSetChanged();
}
((TextView) view.findViewById(R.id.t_datetime)).setText(cashTransactions.get(mTransactionPosition).getDatetime());
return view;
}
public void setTransaction(List<KeyValueParams> mTransaction) {
this.mTransaction = mTransaction;
}
public void setTransactionButtons(List<TransationButton> transactionButtons) {
this.transationButtons = transactionButtons;
}
public void setmTransactionPosition(int position) {
this.mTransactionPosition = position;
}
}
}
As you can see, I'm using ViewPager and and PagerTitleStrip inside Viewpager. Here is my xml code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff"
android:clickable="true">
<LinearLayout
android:id="#+id/u_header"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/u_transaction_details_viewpager_3"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/u_transaction_details_header"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:layout_gravity="top"
android:paddingLeft="#dimen/u_common_margin_left"
android:paddingRight="#dimen/u_common_margin_right"
android:background="#color/u_pink_light"
android:padding="#dimen/u_common_text_size_small"
android:textAlignment="center" />
</android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
When I try to go my Fragment,I have this exception
Can anyone tell me what's wrong in my source or how I can write my code to can run without exceptions in new support library?
You should make TransactionDetailsFragment an entirely separate Java file, or make it a public static class, as the error says.
This has nothing to do with your Gradle dependencies, although you honestly should avoid using a + in any dependency

Why PagerAdapter inside fragment shows only the first view?

This is my PagerAdapter.
public class SlideAdapter extends PagerAdapter{
private List<ImageView> views;
public SlideAdapter (List<ImageView> views){
this.views=views;
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView(views.get(position));
}
#Override
public int getCount() {
return views.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(View container, int position) {
((ViewPager) container).addView(views.get(position));
return views.get(position);
}
}
This is my fragment.
public class sportfragment extends Fragment {
private ViewPager slideviewpager;
private Boolean isContinue=true;
private AtomicInteger what=new AtomicInteger (0);
private ImageView[] indiimageview;
private List<ImageView> pics;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public sportfragment() {
}
public static sportfragment newInstance(String param1, String param2) {
sportfragment fragment = new sportfragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_sportfragment, container, false);
slideviewpager=(ViewPager) view.findViewById(R.id.slideviewpager);
ViewGroup indicatorgroup=(ViewGroup) view.findViewById(R.id.indicatorgroup);
pics=new ArrayList<ImageView>();
ImageView slide1=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide1);
pics.add(slide1);
ImageView slide2=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide2);
pics.add(slide2);
ImageView slide3=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide3);
pics.add(slide3);
ImageView slide4=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide4);
pics.add(slide4);
indiimageview=new ImageView[pics.size()];
for (int i=0;i<pics.size();i++) {
ImageView buff=new ImageView(view.getContext());
buff.setLayoutParams(new LinearLayout.LayoutParams(20,20));
buff.setPadding(5,5,5,5);
indiimageview[i]=buff;
if (i==0) {
indiimageview[i].setBackgroundResource(R.drawable.focus);
}else {
indiimageview[i].setBackgroundResource(R.drawable.blur);
}
indicatorgroup.addView(indiimageview[i]);
}
slideviewpager.setAdapter(new SlideAdapter(pics));
slideviewpager.setOnPageChangeListener(new GuidePageChangeListener());
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private final class GuidePageChangeListener implements ViewPager.OnPageChangeListener{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i=0;i<indiimageview.length;i++) {
if (i==position) {
//4 points change with viewpager
indiimageview[i].setBackgroundResource(R.drawable.focus);
} else {
indiimageview[i].setBackgroundResource(R.drawable.blur);
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
}
First page is the Image.
But other 3 is blank.
Is there any way to solve this?
ViewPagers are meant to be used with fragments, not views. This means that you should be packaging your ImageViews as Fragments rather than plain old views.
Consider the following example:
MyImageView.java
public class MyImageFragment extends Fragment {
private ImageView mImageView;
private int resourceId;
public static MyImageFragment newInstance(int resourceId) {
MyImageFragment fragment = new MyImageFragment();
Bundle args = new Bundle();
args.putInt("resource_id", resourceId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle args = getArguments();
if (args != null && !loadedFromArgs) {
url = (String)args.getSerializable("url");
resourceId = args.getInt("in_list", -1);
loadedFromArgs = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_my_image, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image);
mImageView.setBackgroundDrawable(getResources().getDrawable(resourceId))
return rootView;
}
}
fragment_my_image.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Now, instead of a list of ImageViews, you will have a list of MyImageFragments that your PagerAdapter will point to.

Inflated layout from viewpager is null after created view

When I add the viewpager fragment everything goes nice, but when I move to another apps and returns to my app, I have a weird problem that getView or inflated is null. It is showing the view, but I can't have access to it.
Here comes the Fragment that will be used in the ViewPager:
public class FragmentRestauranteBandejao extends Fragment {
JSONObject dados;
View inflated;
ExpandableListView cardapio;
List<String> refeicoes;
List<String> pratos_almoco;
List<String> pratos_janta;
Map<String, List<String>> bandejao = null;
ExpandableListAdapter adapter;
public static FragmentRestauranteBandejao newInstance(String restaurante){
FragmentRestauranteBandejao frag = new FragmentRestauranteBandejao();
Bundle args = new Bundle();
args.putString("restaurante", restaurante);
frag.setArguments(args);
return frag;
}
public void getDados(){
if(dados == null){
if(USPRestaurantes.getDados()){
dados = USPRestaurantes.getCardapioByRestaurante(getArguments().getString("restaurante"));
}else{
Log.d("debug", "Dados ainda não estão prontos");
return;
}
}
if(inflated == null){
Log.d("debug", "inflated eh null");
if(inflated == null){
return;
}
}
//... some code here that deals with the data that comes from a request made at USPRestaurantes.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflated = inflater.inflate(R.layout.fragment_cardapio, container, false);
return inflated;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
inflated = view;
prepararCardapio();
getDados();
}
public void prepararCardapio(){
cardapio = (ExpandableListView) getView().findViewById(R.id.cardapio);
cardapio.setClickable(true);
refeicoes = new ArrayList<String>(Arrays.asList("Almoço","Jantar"));
pratos_almoco = new ArrayList<String>();
pratos_janta = new ArrayList<String>();
pratos_almoco.add("");
pratos_janta.add("");
bandejao = new LinkedHashMap<String, List<String>>();
bandejao.put(refeicoes.get(0), pratos_almoco);
bandejao.put(refeicoes.get(1), pratos_janta);
adapter = new ExpandableListViewAdapter(getActivity(), refeicoes, bandejao);
cardapio.setAdapter(adapter);
}
ViewPager Fragment:
public class FragmentBandejoes extends Fragment{
private String[] tabs = {"Central", "Química", "Física"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ArrayList<Fragment> paginasBandeco;
public int dia_semana = 0;
ProgressDialog dialog;
private TabPageIndicator mIndicator;
int number = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
paginasBandeco = new ArrayList<Fragment>();
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("central"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("quimica"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("fisica"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflated = inflater.inflate(R.layout.fragment_bandejoes, container, false);
return inflated;
}
public void notifyFragments(){
for(int i=0; i<3; i++){
((FragmentRestauranteBandejao) mAdapter.getItem(i)).getDados();
}
if(dialog != null){
dialog.dismiss();
}
}
public void getCardapios(boolean update){
if(!USPRestaurantes.getDados() || update){
boolean request_made = USPRestaurantes.getCardapio(getActivity());
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
getCardapios(false);
viewPager = (ViewPager) getView().findViewById(R.id.pager_bandejoes);
mAdapter = new TabsPagerAdapter(((MainActivity) getActivity()).fragmentManager, paginasBandeco, tabs);
viewPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator) getActivity().findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mIndicator.setCurrentItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
And Finally the FragmentStatePagerAdapter:
public class FragmentBandejoes extends Fragment{
private String[] tabs = {"Central", "Química", "Física"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ArrayList<Fragment> paginasBandeco;
public int dia_semana = 0;
ProgressDialog dialog;
private TabPageIndicator mIndicator;
int number = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
paginasBandeco = new ArrayList<Fragment>();
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("central"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("quimica"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("fisica"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflated = inflater.inflate(R.layout.fragment_bandejoes, container, false);
return inflated;
}
public void notifyFragments(){
for(int i=0; i<3; i++){
((FragmentRestauranteBandejao) mAdapter.getItem(i)).getDados();
}
if(dialog != null){
dialog.dismiss();
}
}
public void getCardapios(boolean update){
if(!USPRestaurantes.getDados() || update){
boolean request_made = USPRestaurantes.getCardapio(getActivity());
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
getCardapios(false);
viewPager = (ViewPager) getView().findViewById(R.id.pager_bandejoes);
mAdapter = new TabsPagerAdapter(((MainActivity) getActivity()).fragmentManager, paginasBandeco, tabs);
viewPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator) getActivity().findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mIndicator.setCurrentItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
Additional Info: When I swipe to the other tabs, the view gets recreated and then it shows the data.
Thanks in advance
From what I can tell reading you code is that you are not taking into consideration the fragment's lifecycle.
Fragments, as Activities, have Lifecycle methods that you should use in order for them to render correctly. I suggest using the onResume callback and with it check if you have any data to display. If you do display them in your fragment. If you don't do what you do when you create the fragmet

how do i use view pager with touchimageview

I am currently using TouchImageView to allow zooming in and out but now, I need also a View Pager using image view. How do I merge those two together? must I inflate the layout?
this is my viewpager
public class Main extends FragmentActivity implements AdapterView.OnItemSelectedListener, ViewPager.OnPageChangeListener{
private ViewPager viewPager;
String[] mImageIds;
private Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayImage();
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(this);
//gallery = (Gallery) findViewById(R.id.gallery);
//gallery.setAdapter(new ImageAdapter());
//gallery.setOnItemSelectedListener(this);
//textView = (TextView) findViewById(R.id.title);
handler = new Handler();
}
public void displayImage()
{
ArrayList<String> mStringList= new ArrayList<String>();
File strPath = new File(Environment.getExternalStorageDirectory() + "/Covers");
int lists = strPath.listFiles().length;
Log.d("number of items in array ",String.valueOf(lists));
File yourDir = new File(strPath, "");
for (File f : yourDir.listFiles()) {
if (f.isFile())
{
String name = f.getName();
String v = strPath + "/" + name;
mStringList.add(v);
}
}
mImageIds = new String[mStringList.size()];
mImageIds = mStringList.toArray(mImageIds);
for(int i = 0; i < mImageIds.length ; i++){
//Log.d("string is",(mImageIds[i]));
}
}
// gallery item selected
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
updateUI(i);
}
// view pager item selected
public void onPageSelected(int i) {
updateUI(i);
}
private void updateUI(final int i) {
handler.post(new Runnable() {
public void run() {
//gallery.setSelection(i);
viewPager.setCurrentItem(i);
///textView.setText("Photo #" + i);
}
});
}
public void onNothingSelected(AdapterView<?> adapterView) { }
public void onPageScrolled(int i, float v, int i1) { }
public void onPageScrollStateChanged(int i) { }
public class ImageAdapter extends BaseAdapter implements OnTouchListener {
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(Main.this);
imageView.setOnTouchListener(this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
public class EnableDisableViewPager extends ViewPager {
private boolean enabled = true;
public EnableDisableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if(enabled)
return super.onInterceptTouchEvent(arg0);
return false;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mImageIds.length;
}
#Override
public Fragment getItem(final int position) {
return new Fragment() {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = new ImageView(Main.this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
return imageView;
}
};
}
}
}
and its xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout android:layout_height="0px"
android:layout_width="fill_parent"
android:layout_weight="1"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip" />
</FrameLayout>
</LinearLayout>
Create an FragmentActivity whose layout consists of View Pager.
Add a Fragment foreach image whose layout consists of
TouchImageView.
Add these list of fragments to the View pager. Thats it. Pinch Zoom and pager both works.
Like this:
#Override
protected void onStart() {
super.onStart();
List<Fragment> fragments = new Vector<Fragment>();
String url1 = "someurl1.jpg";
Bundle Image1 = new Bundle();
Image1.putString("image_url", url1);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image1));
String url2 = "someurl2.jpg";
Bundle Image2 = new Bundle();
Image2.putString("image_url", url2);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image2));
//and so on.
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.animate();
mPager.setAdapter(this.mPagerAdapter);
}

Categories

Resources