FirebaseRecyclerAdapter OnItemClick从片段到片段

时间:2019-03-25 13:41:49

标签: java android android-fragments android-fragmentactivity

我正在片段上使用firebaseRecyclerAdaper,我想从firebase的填充列表中打开一个项目,然后将数据发送到新片段。你们能告诉我如何从FragmentAllPosts上的onCLickListener启动FragmentDetail并将PostModel参数传递给它吗?

主要活动:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar =  findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    progressDialog= new ProgressDialog(this);
    progressDialog.setMessage("Please wait!");
    progressDialog.setCanceledOnTouchOutside(false);


    //Initialize Firebase modules
    firebaseAuth=FirebaseAuth.getInstance();
    databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
    postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
    profileImgRef= FirebaseStorage.getInstance().getReference();


    DrawerLayout drawer = (DrawerLayout)  findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView)  findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);

    circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
    nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
    emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
    if (firebaseAuth.getCurrentUser()!=null){
        LoadUserData(CheckUserDataBase());
    }

    ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
    PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
    vp_pages.setAdapter(pagerAdapter);

    TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
    tbl_pages.setupWithViewPager(vp_pages);
    tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
    tbl_pages.setHorizontalScrollBarEnabled(true);


    fab  = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            fragment= new AddPostFrag();
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction= fragmentManager.beginTransaction();
            transaction.add(R.id.add_post_container, fragment).commit();
            fab.hide();

        }
    });



}

class FragmentAdapter extends FragmentPagerAdapter {

    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new FragmentAllPosts();
            case 1:
                return new FragmentLosts();
            case 2:
                return new FragmentFounds();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            //
            //Your tab titles
            //
            case 0:return "All";
            case 1:return "Losts";
            case 2: return "Founds";
            default:return null;
        }
    }
}

@Override
protected void onStart() {
    super.onStart();

    FirebaseUser user= firebaseAuth.getCurrentUser();
    if (user == null){
        SendUserToLogin();
    } else {

        CheckUserDataBase();

    }

}



public static class PostsViewHolder extends RecyclerView.ViewHolder {

    CircleImageView circleImageView;
    ImageView imageView;
    TextView authorNdate, location, description;

    public PostsViewHolder(@NonNull View itemView) {
        super(itemView);

        circleImageView= itemView.findViewById(R.id.circleImageView_cv);
        imageView= itemView.findViewById(R.id.imageView_cv);
        authorNdate= itemView.findViewById(R.id.author_date_cv);
        location = itemView.findViewById(R.id.location_cv);
        description = itemView.findViewById(R.id.description_cv);



    }
}

private void UpdateHome() {

}

private void LoadUserData(final String uid) {
    try {
        final File localFile =File.createTempFile("profile","png");
        StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");


        filepath.getFile(localFile)
        .addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                Picasso.get()
                        .load(localFile)
                        .placeholder(R.drawable.ic_account)
                        .into(circleImageViewMain);

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this,
                        "Profile photo not found, please update your profile!",
                        Toast.LENGTH_SHORT).show();
                SendUserToSetup();

            }
        });

    } catch (IOException e) {
        e.printStackTrace();
    }

    databaseReference.child(uid).child("userInfo").addValueEventListener(
            new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if (dataSnapshot.hasChild("name")){
                        String name = dataSnapshot.child("name").getValue().toString();
                        nameEdtTxt.setText(name);
                        String email = dataSnapshot.child("email").getValue().toString();
                        emailEdtTxt.setText(email);


                    } else {
                        Toast.makeText(MainActivity.this,
                                "Profile name does not exists, please update your profile",
                                Toast.LENGTH_SHORT).show();
                    }



                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            }
    );
}



@Override
protected void onStop() {
    super.onStop();
}

private String CheckUserDataBase() {
    final String userID =firebaseAuth.getCurrentUser().getUid();
    databaseReference.addValueEventListener(
            new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (!dataSnapshot.child(userID).hasChild("userInfo")){
                        SendUserToSetup();
                    } else {
                        UpdateHome();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            }
    );

    return userID;
}

private void SendUserToSetup() {
    Intent i = new Intent(this,SetupActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
}

private void SendUserToLogin() {
    Intent i = new Intent(this,LoginActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer =  findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (getSupportFragmentManager().getBackStackEntryCount() >0)
        {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit();

        } else
            {
                super.onBackPressed();

            }

    fab.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    switch (id){
        case R.id.nav_home:
            super.onResume();

            if (fragment!=null){
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction= fragmentManager.beginTransaction();
                transaction.remove(fragment).commit();
                fab.show();

            }

            break;

        case R.id.nav_profile:
            super.onPause();
            break;

        case R.id.nav_my_posts:
            super.onPause();
            break;

        case R.id.nav_messeges:
            super.onPause();
            break;

        case R.id.nav_settings:
            super.onPause();
            break;

        case R.id.nav_logout:
            SendUserToLogin();
            firebaseAuth.signOut();

            break;
    }

    DrawerLayout drawer =  findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

带有FirebaseRecyclerAdapter的片段

public class FragmentAllPosts extends Fragment {
// 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";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;

public FragmentAllPosts() {
    // Required empty public constructor
}

public static FragmentAllPosts newInstance(String param1, String param2) {
    FragmentAllPosts fragment = new FragmentAllPosts();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    progressDialog= new ProgressDialog(getActivity());

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
   View v = inflater.inflate(R.layout.fragment_all_posts,container,false);

    postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
    recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);
    recyclerAllPosts.setLayoutManager(linearLayoutManager);

    return v;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context=context;
}

@Override
public void onStart() {
    super.onStart();

    progressDialog.show();
    FirebaseRecyclerOptions<PostsModel> options=
            new FirebaseRecyclerOptions.Builder<PostsModel>()
            .setQuery(postsRef,PostsModel.class)
            .setLifecycleOwner(this)
            .build();

    FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
            new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull final PostsViewHolder holder, int position, @NonNull final PostsModel model) {



                    String processedTime= CalculateTime(model.getData());
                    Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
                    Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
                    holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
                    holder.location.setText(model.getLocation());
                    holder.description.setText(model.getDescription());



                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Fragment frag= new FragmentDetail();
                            getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
                                    .addToBackStack(null).commit();
                        }
                    });
                }
                @NonNull
                @Override
                public PostsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                    View view= LayoutInflater.from(viewGroup.getContext())
                            .inflate(R.layout.card_view,viewGroup,false );
                    PostsViewHolder viewHolder= new PostsViewHolder(view);

                    return viewHolder;
                }
            };
    recyclerAllPosts.setAdapter(adapter);
    progressDialog.dismiss();
    adapter.startListening();
}



// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}


public String CalculateTime(String inputTime){
    String timeOut;

    Calendar currentTime= Calendar.getInstance();
    SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
    dateFormat.format(currentTime.getTime());

    SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
    Calendar postTime = Calendar.getInstance();

    try {
        Date datePost=postFormat.parse(inputTime);
        postTime.setTime(datePost);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    long timeCurrent= currentTime.getTimeInMillis();
    long timePost = postTime.getTimeInMillis();
    long diff= timeCurrent- timePost;

    long minutes= diff/(60*1000);
    long hours = diff/(60 * 60 * 1000);
    long days = diff/(24 * 60 * 60 * 1000);

    if (minutes<59 && minutes>1){
        timeOut=Long.toString(minutes)+" mins ago";

    } else if (minutes<1){
        timeOut=" just now";

    }else if (hours<24 && minutes>59){
        timeOut=Long.toString(hours)+" hour(s) ago";

    }else {
        timeOut=Long.toString(days)+" day(s) ago";
    }

    return timeOut;

}

static class PostsViewHolder extends RecyclerView.ViewHolder {

    CircleImageView circleImageView;
    ImageView imageView;
    TextView authorNdate, location, description;

    public PostsViewHolder(@NonNull View itemView) {
        super(itemView);
        itemView.setTag(this);
        circleImageView= itemView.findViewById(R.id.circleImageView_cv);
        imageView= itemView.findViewById(R.id.imageView_cv);
        authorNdate= itemView.findViewById(R.id.author_date_cv);
        location = itemView.findViewById(R.id.location_cv);
        description = itemView.findViewById(R.id.description_cv);




    }
}


@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}


public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

详细片段:

public class FragmentDetail extends Fragment {


public FragmentDetail() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_detail, container, false);
}

}

1 个答案:

答案 0 :(得分:0)

我建议您阅读文档。在两个活动之间传递数据应该通过接口来完成。 As suggested by the official site