当前位置:  开发笔记 > Android > 正文

如何使用ViewPager实现Firebase?

如何解决《如何使用ViewPager实现Firebase?》经验,为你挑选了1个好方法。

使用ViewPager的firebase的最佳方法是什么.

预期产出

期待OutPut

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

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;
    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 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, 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

public class MyFragment extends Fragment {
    private TextView upperText;
    private TextView lowerText;
    List 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中实现了它,它就像魅力一样

FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter(
                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);
        }
    }

AndroidBegin.. 5

最后,在SO和各种其他博客上努力工作之后,我能够使用我从中获得的数据,Firebase非常类似于ViewPager:Horizontal RecyclerViewwith LinearSnapHelper.你需要覆盖findTargetSnapPosition,然后你就完成了.

首先将RecyclerView添加到您的Activity/Fragment中


    

在我的情况下,我使用了CardView内部RecyclerView

blog_row.xml




        

            

            

            
        

    

在你的活动/片段中

    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效果.

RecyclerView ViewPager

图像来源



1> AndroidBegin..:

最后,在SO和各种其他博客上努力工作之后,我能够使用我从中获得的数据,Firebase非常类似于ViewPager:Horizontal RecyclerViewwith LinearSnapHelper.你需要覆盖findTargetSnapPosition,然后你就完成了.

首先将RecyclerView添加到您的Activity/Fragment中


    

在我的情况下,我使用了CardView内部RecyclerView

blog_row.xml




        

            

            

            
        

    

在你的活动/片段中

    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效果.

RecyclerView ViewPager

图像来源

推荐阅读
oDavid_仔o_880
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有