简体   繁体   中英

pass value from activity to fragment using bundle in tabbed activity

I am a java-illiterate, and still trying to develop a app for my personal use. I have started with android-studio's "Tabbed-Activity", and mostly unaltered except a fragment and a bundle in MainActivity.

Here are my codes:

MainActivity

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
    private static final String TAG = MainActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //FloatingActionButton fab = findViewById(R.id.fab);
        Bundle bundle = new Bundle();
        bundle.putDouble("loclat", 25.4358);
        bundle.putDouble("loclang",81.8463);
        Fragment SunFragment = new SunFragment();
        SunFragment.setArguments(bundle);

        setContentView(R.layout.activity_main);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
    }
}

SectionsPagerAdapter

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        //return PlaceholderFragment.newInstance(position + 1);
        switch (position) {
            case 0:
                return new SunFragment();
            //return PlaceholderFragment.newInstance(pos + 5);
            case 1:
                return PlaceholderFragment.newInstance(1);
            //return SecondFragment.newInstance();
            //return PlaceholderFragment.newInstance(pos + 1);
            default:
                return PlaceholderFragment.newInstance(2);
        }
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 3;
    }
}

And finally, The SunFragment , where I want my bundled data from MainActivity:

public class SunFragment extends Fragment {

    List<SunSession> sunsList;
    Typeface sunfont;
    Double Dlat;
    Double Dlang;

    //to be called by the MainActivity
    public SunFragment() {
        // Required empty public constructor
    }


    private static final String KEY_LOCATION_NAME = "location_name";
    public String TAG ="SunFragment";
    public String location;//="No location name found";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve location and camera position from saved instance state.
        if (savedInstanceState != null) {
            location = savedInstanceState.getCharSequence(KEY_LOCATION_NAME).toString();
            System.out.println("OnCreate location  "+location);
           // Dlat = getArguments().getDouble("loclat");
            //Dlang = getArguments().getDouble("loclang");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_sun, container, false);
        //onSaveInstanceState(new Bundle());
        if (getArguments() != null) {
            Dlat = getArguments().getDouble("loclat");
            Dlang = getArguments().getDouble("loclang");
        } else {
            Dlat=23.1;
            Dlang=79.9864;
        }

        Log.e("Lat", Double.toString(Dlat));

I have followed this blog to make it, but no value is passed. Kindly help.

NB. This is a better described, and detailed question of my earlier question , which I understand, needs more code to be shown.

In your MainActivity , your sunFragment is unused. Remove this part:

/*Bundle bundle = new Bundle();
bundle.putDouble("loclat", 25.4358);
bundle.putDouble("loclang",81.8463);
Fragment SunFragment = new SunFragment();
SunFragment.setArguments(bundle);*/

You have to set bundle to fragment inside your SectionsPagerAdapter

case 0:
    Bundle bundle = new Bundle();
    bundle.putDouble("loclat", 25.4358);
    bundle.putDouble("loclang",81.8463);

    Fragment sunFragment = new SunFragment();
    sunFragment.setArguments(bundle);

    return sunFragment;

But if you need to set the bundle to fragment from MainActivity . Then use a callback in that purpose.

This way you can pass data from your mainActivity to fragment

MainActivity onCreate method

     adapter = new Adapter(getChildFragmentManager());

     SquadsTeamListFragment  teamA =                
        SquadsTeamListFragment.newInstance(teamAData,teamBData
        adapter.addFragment(teamA, teamAName);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

use this adapter in your main activity

 static class Adapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    Adapter(FragmentManager manager) {
        super(manager);
    }
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }
    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
    @Override
    public CharSequence getPageTitle(int position){
        return mFragmentTitleList.get(position);
     }
  }

receive data to fragment (SquadsTeamListFragment .java)

   public static SquadsTeamListFragment newInstance(String playerList, String   
  oppPlayerList) {
    SquadsTeamListFragment fragment = new SquadsTeamListFragment();
    Bundle args = new Bundle();
    args.putString(ARG_TEAM_DATA, playerList);
    args.putString(ARG_OPP_TEAM_DATA, oppPlayerList);

    fragment.setArguments(args);
    return fragment;
}
   @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        playerList = getArguments().getString(ARG_TEAM_DATA);
        oppPlayerList = getArguments().getString(ARG_OPP_TEAM_DATA);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM