如何从片段开始向活动添加片段?

时间:2017-12-28 06:46:02

标签: java android android-fragments

我从fragment A开始Activity,然后从fragment B开始fragment A。但问题是在fragment B上调用onActivityResult时未显示添加fragment Bcontext的{​​{1}}也变为空。

从活动开始片段A的代码,

fragment B

从片段A开始片段B的代码,

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentA fragment = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.commit();

4 个答案:

答案 0 :(得分:2)

不要用片段A中的片段B替换片段A,而是尝试将它们替换为活动本身。

((MyActivity) getActivity()).switchToSecondFragment(); 

在活动中的switchToSecondFragment方法中:

public void switchToSecondFragment(){
     FragmentManager manager = getSupportFragmentManager();
     FragmentB fragment = new SelectTipFragment();
     FragmentTransaction transaction = manager.beginTransaction();
     transaction.replace(R.id.container, fragment).addToBackStack(null);
     transaction.commit();
}

答案 1 :(得分:0)

getSupportFragmentManager()上使用getFragmentManager()代替FragmentA

FragmentManager manager = getSupportFragmentManager();
FragmentB fragment = new SelectTipFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment).addToBackStack(null);
transaction.commit();

答案 2 :(得分:0)

使用以下方法从活动或片段切换片段

public class MainActivity extends AppCompatActivity {
    ......

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pedometer);

        Toolbar toolbar  = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        User user = new User();
        user.checkLogin(MainActivity.this);

        tabLayout = (TabLayout)findViewById(R.id.tabs);
        viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        viewPager.setOffscreenPageLimit(2);

        //runnable to get rid of bug
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        setTitle("Updates");
        //get locations from db
        getPOISFromDB();
    }//end method onCreate

    private class MyAdapter extends FragmentStatePagerAdapter {

        private MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 :
                    return new FirstFragment();
                case 1 :
                   eturn new SecondFragment();

                case 2 :
                    return new PointOfInterestMapFragment();

            }
            return null;
        }

        @Override
        public int getCount() {

            return 3;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return getResources().getString(R.string.fragment_1);
                case 1 :
                    return getResources().getString(R.string.fragment_2);
                case 2 :
                    return getResources().getString(R.string.fragment_3);

            }
            return null;
        }

    }//end class MyAdapter  

    private  void getPOISFromDB(){
        // Tag used to cancel the request
        String tag_string_req = "req_poi_list";

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_POI_LIST, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response: " + response);

                try {
                    JSONObject jObj = new JSONObject(response);
                    JSONArray jsonArray = jObj.getJSONArray("pois");
                    PointOfInterestLab.get(AppController.getInstance()).clearPointOfInterests();

                    for(int i=0; i < jsonArray.length(); i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int id = jsonObject.getInt("poi_id");
                        String name = jsonObject.getString("name");
                        String summary = jsonObject.getString("summary");
                        double latitude =  jsonObject.getDouble("latitude");
                        double longitude = jsonObject.getDouble("longitude");
                        Location location = new Location("dummyProvider");
                        location.setLatitude(latitude);
                        location.setLongitude(longitude);

                        PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
                                , location);
                        PointOfInterestLab.get(AppController.getInstance()).addPointOfInterest(pointOfInterest);

                    }

                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Server error: " + error.getMessage());

            }
        }) {

            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                SQLiteHandler sqLiteHandler = new SQLiteHandler(AppController.getInstance());
                User user = sqLiteHandler.getUserDetails();
                params.put("user_id", user.getUserID());
                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    }//end method getPOISFromDB
}

将此方法称为:

switchContent(mainListingFragment,false,String.valueOf(MAIN_LISTING_FRAGMENT));

int MAIN_LISTING_FRAGMENT = 1; //你可以在KeyInterface中声明这个

public int switchContent(Fragment fragment, boolean isAddBackStack, String tag) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, fragment, tag);

        if (isAddBackStack) {
            ft.addToBackStack(null);
        }

        int commitID = ft.commitAllowingStateLoss();
        setCurrentTopFragment(Integer.parseInt(tag));
        return commitID;

    }

AND yes导入以下依赖项:

public interface KeyInterface {
   int MAIN_LISTING_FRAGMENT = 1;
}

答案 3 :(得分:0)

在活动的xml布局中使用以下代码,使用 FrameLayout 作为容器: -

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>

在您的活动的java代码中编写此代码以添加片段

public void addFragment(Fragment fragment) {

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.main_parent, fragment);
            fragmentTransaction.commitAllowingStateLoss();
    }

请注意: -

fragmentTransaction.add(R.id.main_parent, fragment); 

将在容器中添加片段

 fragmentTransaction .replace(R.id.main_parent, fragment);

将删除之前添加的容器,并添加新的容器HERE

现在在您的活动中调用上述功能。

        TracksSubGridViewFragment tracksSubGridViewFragment = new TracksSubGridViewFragment();
addFragment(tracksSubGridViewFragment);

或像你这样的片段

TracksSubGridViewFragment tracksSubGridViewFragment = new TracksSubGridViewFragment();
     ((MainActivity) getActivity()).addFragment(tracksSubGridViewFragment);