本文介绍了如何使用ViewPager实施Firebase?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Firebase与ViewPager一起使用的最佳方法是什么.

What is the best way to use firebase with ViewPager.

预期产量

如何将ViewPager与Firebase一起使用,以便它通知Firebase该位置并相应地获取并附加数据?

How can I use ViewPager with Firebase such that it notifies the firebase for the position and gets and attaches the data accordingly?

Person.java

public class Person {

    private String name;
    private String email;
    private String hobby;

    public Person(){

    }


    public Person(String name , String email , String hobby){
        this.name= name;
        this.email = email;
        this.hobby = hobby;

    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public String getHobby() {
        return hobby;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
//    private FirebaseAuth mAuth;
    List<Person> person;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        person = new ArrayList<>();
//        mAuth = FirebaseAuth.getInstance();
        context = this;



        viewPager = (ViewPager) findViewById(R.id.pagerView);
        viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), person, context));


    }


    class MyPagerAdapter extends FragmentPagerAdapter {
        String[] tabsArray;
        private List<Person> personInAdapter = new ArrayList<>();
        private Context context;

//        int icons[] = {R.drawable.white_home, R.drawable.white_heart,
//                R.drawable.white_star, R.drawable.white_heart, R.drawable.white_star};

        public MyPagerAdapter(FragmentManager fm, List<Person> person, Context context) {
            super(fm);
            personInAdapter = person;
            this.context = context;
            tabsArray = getResources().getStringArray(R.array.TABS);
        }


//        @Override
//        public CharSequence getPageTitle(int position) {
//            return tabsArray[position];
//        }

        @Override
        public Fragment getItem(int position) {

            return MyFragment.getInstance(position );
        }

        @Override
        public int getCount() {
            return personInAdapter.size();
        }
    }
}

MyFragment.java

MyFragment.java

public class MyFragment extends Fragment {
    private TextView upperText;
    private TextView lowerText;
    List<Person> personInAdapter = new ArrayList<>();
    private Context context;
    private DatabaseReference databaseReference;
    public static MyFragment getInstance(int position) {
        MyFragment myFragment = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        myFragment.setArguments(args);

        return myFragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        upperText = (TextView) view.findViewById(R.id.myFragmentUpperText);
        lowerText = (TextView) view.findViewById(R.id.myFragmentLowerText);
        databaseReference = FirebaseUtil.getBaseRef().child("Person");
        int i = getArguments().getInt("position");
         ValueEventListener postListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
            // Get Post object and use the values to update the UI
            for (DataSnapshot personSnapshot: dataSnapshot.getChildren()) {
                Person person = personSnapshot.getValue(Person.class);
                upperText.setText(person.getName());
                lowerText.setText(person.getEmail());
                Log.i("Data In Person  ", person.toString());
            }

            // [END_EXCLUDE]
        }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                // [START_EXCLUDE]

            }
        };
       databaseReference.addValueEventListener(postListener);
//        Bundle bundle = getArguments();
//        if (bundle != null) {
//            textView.setText("The value is" +i);
//        }

        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }
}

我已经尝试过使用FirebaseRecyclerView来尝试使用Firebase,并在自定义Recyclerview中实现相同的功能,并且它就像魅力一样

I have tried firebase with the FirebaseRecyclerView and implemented the same in a custom Recyclerview and it worked like charm

FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
                Blog.class,
                R.layout.blog_row,
                BlogViewHolder.class,
                mDatabaseReference
        ) {
            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
                viewHolder.setDesc(model.getDesc());
                viewHolder.setTitle(model.getTitle());
                viewHolder.setImage(getApplicationContext(), model.getImageUrl());
                mGoogleNow.progressiveStop();
                mGoogleNow.setVisibility(View.GONE);
            }
        };
        mBlogList.setAdapter(firebaseRecyclerAdapter);
    }
    public void LogoutFromFirebase(View view) {
        mAuth.signOut();
    }
    public static class BlogViewHolder extends RecyclerView.ViewHolder {
        NetworkImageView networkImageView;
        ImageLoader imageLoader;
        View mView;
        public BlogViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }
        public void setTitle(String title) {
            TextView sTitle = (TextView) mView.findViewById(R.id.TitleTextView);
            sTitle.setText(title);
        }
        public void setDesc(String desc) {
            TextView sDesc = (TextView) mView.findViewById(R.id.descriptionTextView);
            sDesc.setText(desc);
        }
        public void setImage(Context context, String image) {
            networkImageView = (NetworkImageView) mView.findViewById(R.id.imageBlogPost);
            imageLoader = CustomVolleyRequest.getInstance(context)
                    .getImageLoader();
            imageLoader.get(image, ImageLoader.getImageListener(networkImageView,
                    R.drawable.crop_image_menu_crop, android.R.drawable
                            .ic_dialog_alert));
            networkImageView.setImageUrl(image, imageLoader);
           // Picasso.with(context).load(image).into(networkImageView);
        }
    }

推荐答案

最后,在SO和其他各种博客上苦苦挣扎之后,我得以将从Firebase获得的数据用于与ViewPager非常相似的内容: Horizontal RecyclerViewLinearSnapHelper.您需要覆盖findTargetSnapPosition,然后完成.

Finally after toiling hard on SO and various other blogs I was able to use the data I get from the Firebase into something very similar to ViewPager : Horizontal RecyclerView with LinearSnapHelper. You need to override findTargetSnapPosition and then you are done.

首先将RecyclerView添加到您的活动/片段"

<android.support.v7.widget.RecyclerView
        android:layout_below="@+id/sign_in_button"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:id="@+id/blog_list"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

在我的情况下,我在RecyclerView

blog_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 

    xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/imageBlogPost"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:paddingBottom="15dp"
                android:src="@drawable/common_google_signin_btn_text_light_normal" />

            <TextView
                android:id="@+id/TitleTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
               android:layout_marginBottom="20dp"

                android:text="Post Title Here"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/descriptionTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Post Description Here"
                android:paddingBottom="15dp"
                android:textSize="14sp" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

在您的活动/片段中

    private RecyclerView mBlogList;




 LinearLayoutManager layoutManager
                    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
            mBlogList = (RecyclerView) findViewById(R.id.blog_list);

            mBlogList.setHasFixedSize(true);
            mBlogList.setLayoutManager(layoutManager);

LinearSnapHelper snapHelper = new LinearSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager lm, int velocityX, int velocityY) {
                View centerView = findSnapView(lm);
                if (centerView == null)
                    return RecyclerView.NO_POSITION;

                int position = lm.getPosition(centerView);
                int targetPosition = -1;
                if (lm.canScrollHorizontally()) {
                    if (velocityX < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                if (lm.canScrollVertically()) {
                    if (velocityY < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                final int firstItem = 0;
                final int lastItem = lm.getItemCount() - 1;
                targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
                return targetPosition;
            }
        };
        snapHelper.attachToRecyclerView(mBlogList);

最后一步是将适配器设置为RecyclerView

mBlogList.setAdapter(firebaseRecyclerAdapter);

使用此方法,我们可以像这样获得ViewPager效果.

Using this we can get ViewPager Effect Like this.

图片来源

这篇关于如何使用ViewPager实施Firebase?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 20:25