使用选项卡式活动中的捆绑将值从活动传递到片段

时间:2019-12-05 08:01:15

标签: java android bundle

我是个Java文盲,并且仍在尝试开发供个人使用的应用程序。 我是从android-studio的“ Tabbed-Activity”开始的,除了MainActivity中的一个片段和一个捆绑包外,大部分都没有改变。

这是我的代码:

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

最后,是 SunFragment ,我希望从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));

我已经关注this博客,但是没有传递任何值。请帮助。

NB。这是一个更好描述的问题,my earlier question的详细问题据我所知,需要显示更多代码。

2 个答案:

答案 0 :(得分:1)

在您的MainActivity中,您的sunFragment未使用。删除此部分:

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

您必须在bundle内将fragment设置为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;

但是如果您需要将bundle的{​​{1}}设置为fragment。然后为此目的使用MainActivity

答案 1 :(得分:0)

通过这种方式,您可以将数据从mainActivity传递到片段

MainActivity onCreate方法

     adapter = new Adapter(getChildFragmentManager());

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

在您的主要活动中使用此适配器

 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);
     }
  }

接收数据以分段(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);

    }
}