将值从主活动传递到选项卡片段

时间:2016-06-11 16:11:54

标签: java android android-fragments

我需要将MainActivity中的值传递给我的标签Fragments,以便我可以相应地使用该值。任何帮助将不胜感激。提前谢谢。

主要活动:

    //Value from Login Activity. The value I need to pass    
    Intent intent = getIntent();
    String username = intent.getStringExtra("username");

    //Menu on my Drawer
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
    mDrawerLayout.closeDrawers();

    if (menuItem.getItemId() == R.id.nav_request) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.containerView,new RequestFragment()).commit();
    }

    if (menuItem.getItemId() == R.id.nav_requisitions) {
        FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
        xfragmentTransaction.replace(R.id.containerView,new RequisitionsFragment()).commit();
    }
    return false;
}

});   

3个标签属于RequisitionsFragment()。这是我需要传递用户名值的地方。

这是我的RequisitionsFragment()

    public class RequisitionsFragment extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View x =  inflater.inflate(R.layout.tab_layout,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        return x;
    }


    class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new PendingFragment();
                case 1 : return new ApprovedFragment();
                case 2 : return new CompletedFragment();
            }
            return null;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Pending";
                case 1 :
                    return "Approved";
                case 2 :
                    return "Completed";
            }
            return null;
        }
    }
}

这是我需要使用值PendingFragment()的部分:

public class PendingFragment extends Fragment {
.....
......    
private void sendRequest(){

            StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL,
                    new Response.Listener<String>()
                    {
                        @Override
                        public void onResponse(String response) {
                            showJSON(response);
                        }
                    },
                    new Response.ErrorListener()
                    {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(PendingFragment.this.getActivity(),error.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    }
            ) {
                @Override
                protected Map<String, String> getParams()
                {
                    Map<String, String> params = new HashMap<>();
                    params.put("username", username);
                    return params;
                }
            };
            RequestQueue queue = Volley.newRequestQueue(PendingFragment.this.getActivity());
            queue.add(stringRequest);
        }

3 个答案:

答案 0 :(得分:1)

您通过调用RequisitionsFragment来实例化new RequisitionsFragment()。而不是这样做,使用newInstance()方法模式。像这样:

RequisitionsFragment中,声明此方法:

public static RequisitionsFragment newInstance(String username) {
    RequisitionsFragment fragment = new RequisitionsFragment();
    Bundle args = new Bundle();
    args.putString("USERNAME", username);
    fragment.setArguments(args);
    return fragment;
}

在您的MainActivity中,请调用此方法:

 fragmentTransaction.replace(R.id.containerView, RequestFragment.newInstance(username)).commit();

此后,当您需要访问片段内的参数时,请调用

String username = getArguments().getString("USERNAME");

应该这样做。如果这有帮助,请告诉我。

修改

RequisitionsFragment

进行这些更改
public class RequisitionsFragment extends Fragment {

public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
String username;

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

public static RequisitionsFragment newInstance(String username) {
    RequisitionsFragment fragment = new RequisitionsFragment();
    Bundle args = new Bundle();
    args.putString("USERNAME", username);
    fragment.setArguments(args);
    return fragment;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View x =  inflater.inflate(R.layout.tab_layout,null);
    tabLayout = (TabLayout) x.findViewById(R.id.tabs);
    viewPager = (ViewPager) x.findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });
    username = getArguments().getString("USERNAME");
    return x;
}


class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position)
    {
        switch (position){
            case 0 : return PendingFragment.newInstance(username);
            case 1 : return new ApprovedFragment();
            case 2 : return new CompletedFragment();
        }
        return null;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {

        switch (position){
            case 0 :
                return "Pending";
            case 1 :
                return "Approved";
            case 2 :
                return "Completed";
        }
        return null;
    }
}
}

然后在newInstance()内写一个PendingFragment方法:

public class PendingFragment extends Fragment {

String username;

public PendingFragment(){
    //Required empty constructor
}

public static PendingFragment newInstance(String username) {
    PendingFragment fragment = new PendingFragment();
    Bundle args = new Bundle();
    args.putString("USERNAME", username);
    fragment.setArguments(args);
    return fragment;
}
.....//Initialize username inside onCreateView like this:
//username = getArguments().getString("USERNAME");
......    
private void sendRequest(){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        showJSON(response);
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(PendingFragment.this.getActivity(),error.getMessage(),Toast.LENGTH_LONG).show();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                return params;
            }
        };
        RequestQueue queue = Volley.newRequestQueue(PendingFragment.this.getActivity());
        queue.add(stringRequest);
    }

如果有帮助,请告诉我。

答案 1 :(得分:0)

在PagerAdapter()中尝试这样做

 Bundle bundle=new Bundle();
 bundle.putString(.....);
 new PendingFragment().setArgument(bundle);

同样,您可以在Activity

中调用setArgument()函数

答案 2 :(得分:0)

有更好,更强大的方法在类之间发送数据。 Event Bus支持您无法使用构造函数类或接口进行的某些交互。对于动态数据通信,这个第三方库是完美且易于使用的