Android将值从第三个片段传递到第一个片段

时间:2018-07-26 05:51:12

标签: java android

这是我的适配器

viewHolder.Edit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        mAuth=FirebaseAuth.getInstance();
        FirebaseFirestore firebaseFirestore=FirebaseFirestore.getInstance();
        firebaseFirestore.collection("bookings").whereEqualTo("customer",mAuth.getUid())
          .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                for (DocumentSnapshot document : task.getResult()) {
                    currentUserId=document.getId();
                    Log.d("ID", String.valueOf(currentUserId));
                }

                StylistFragment servicesFragment = new StylistFragment();
                AppCompatActivity activity = (AppCompatActivity) view.getContext();
                Bundle bundle=new Bundle();
                bundle.putString("userdocumentid",currentUserId);
                servicesFragment.setArguments(bundle);
                activity.getSupportFragmentManager().beginTransaction()
                  .replace(R.id.frameLayout, servicesFragment).addToBackStack(null).commit();

                // change navigation item color of a fragment when button is clicked
                ((HomeActivity)view.getContext()).changeMenu(R.id.navigation_stylist);
            }
        });
    }
});

这是我的片段,我从第三个片段到第一个片段都在获取价值

public class StylistFragment extends Fragment {
    private RecyclerView recyclerView;
    private String docid;
    CircleImageView stylistImg;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.stylist_recycler, container, false);
        recyclerView=view.findViewById(R.id.stylistRecycler);
        stylistImg=view.findViewById(R.id.stylistImg);

        Bundle bundle=getArguments();
        if(bundle!=null){
            docid=bundle.getString("userdocumentid","");
            Log.d("selectedDocumentId",docid);
        }

        try{
            FirebaseFirestore db = FirebaseFirestore.getInstance();
            try {
                db.collection("stylist").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            try {
                                ArrayList<String> stylistId=new ArrayList<>();
                                for(DocumentSnapshot documentSnapshot:task.getResult()){
                                    String id=documentSnapshot.getId();
                                    stylistId.add(id);
                                }

                                StylistAdapter listAdapter = new StylistAdapter(task,docid,stylistId,stylistImg);
                                RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecorator(ContextCompat.getDrawable(getContext(), R.drawable.divider));
                                recyclerView.addItemDecoration(dividerItemDecoration);
                                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
                                recyclerView.setLayoutManager(layoutManager);
                                recyclerView.setAdapter(listAdapter);

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return view;
    }        
}

我正在将值从第三个片段传递到第一个片段。在第三个片段中,如果recyclerview排除了第一项,我正在使用recyclerview值,该值是我在docid中获得的,但是如果它执行多次,则docid为null我使用了相同的代码,但效果很好,我不知道发生了什么事,现在无法正常工作

2 个答案:

答案 0 :(得分:0)

充分利用接口。

在第三个片段内创建一个接口,并在第一个片段中实现该接口,并从第三个片段中调用带有值的函数。

您可以在第一个片段中使用该值。

答案 1 :(得分:0)

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, StylistFragment.getInstannce("navigation_home")).addToBackStack(null).commit();
                    return true;
                case R.id.navigation_dashboard:
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, StylistFragment.getInstannce("navigation_dashboard")).addToBackStack(null).commit();
                    return true;
                case R.id.navigation_notifications:
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, StylistFragment.getInstannce("navigation_notifications")).addToBackStack(null).commit();
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    public static class StylistFragment extends Fragment {

        private static final String TAG_VALUE = "tag_value";

        public static StylistFragment getInstannce(String myValue){
            Bundle extras = new Bundle();
            extras.putString(TAG_VALUE,myValue);
            StylistFragment fragment = new StylistFragment();
            fragment.setArguments(extras);
            return fragment;
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            final String myStringValue = getArguments().getString(TAG_VALUE);

            Log.d(TAG_VALUE, "My passed Value: " + myStringValue);
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

输出

  

D / tag_value:我传递的值:navigation_home

     

D / tag_value:我传递的值:navigation_dashboard

     

D / tag_value:我传递的值:navigation_notifications