导航抽屉未导航到MainAcvtivity中的片段

时间:2016-07-08 11:00:57

标签: android android-fragments

MainActivity.java

package piestudio.opinion;

import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity
        implements  NavigationView.OnNavigationItemSelectedListener {


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override

    public boolean onNavigationItemSelected(MenuItem item) {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

        int id = item.getItemId();


        if (id == R.id.toi) {

            FragmentOne FragmentOne = new FragmentOne();
            FragmentManager fragmentManager = getFragmentManager();

            fragmentManager.beginTransaction()
                    .add(R.id.content_frame,FragmentOne,"Times of India")
                    .commit();
            drawer.closeDrawer(navigationView);





        } else if (id == R.id.thehindu) {

            } else if (id == R.id.support) {



            }
    return  true;
    }

    }

我想导航到fragmentOne.java

    package piestudio.opinion;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;

/**
 * Created by jene on 7/4/2016.
 */
public class FragmentOne extends Fragment{

    Activity MainActivity;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        MainActivity= activity;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final NavigationView navigationView = (NavigationView)getView().findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener(){

            public boolean onNavigationItemSelected(MenuItem Item){
              int id = Item.getItemId();


            if( id  == R.id.toi) {
                DrawerLayout drawer = (DrawerLayout)getView().findViewById(R.id.drawer_layout);


                FragmentOne FragmentOne = new FragmentOne();
                FragmentManager fragmentManager = getFragmentManager();

                fragmentManager.beginTransaction()
                        .add(R.id.content_frame,FragmentOne,"Times of India")
                        .commit();
                drawer.closeDrawer(navigationView);


        }
                DrawerLayout drawer = (DrawerLayout)getView().findViewById(R.id.drawer_layout);

                drawer.closeDrawer(GravityCompat.START);
                return true;
            }




        }



        );


    }

        }

我的导航抽屉中有3个选项,我想从主要活动移动到片段到相应的导航选项,但我的应用程序没有这样做。 当我点击导航抽屉的第一个选项时,整个应用程序自动退出

logcat的

ion E/AndroidRuntime: FATAL EXCEPTION: main
                                                             java.lang.NullPointerException
                                                                 at piestudio.opinion.FragmentOne.onCreate(FragmentOne.java:36)
                                                                 at android.app.Fragment.performCreate(Fragment.java:1673)
                                                                 at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:854)
                                                                 at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
                                                                 at android.app.BackStackRecord.run(BackStackRecord.java:682)
                                                                 at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
                                                                 at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
                                                                 at android.os.Handler.handleCallback(Handler.java:730)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                 at android.os.Looper.loop(Looper.java:137)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5103)
                                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:525)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                 at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

尝试一次。调用getSupportFragmentManager()而不是getFragmentManager():

例如。

FragmentManager fragmentManager = getSupportFragmentManager();

答案 1 :(得分:0)

Try this code to open a new fragment when click on item of navigation menu.


    /**
     * Insert new fragment.
     *
     * @param fragment
     * @param position
     */
    @SuppressLint("NewApi")
    private void initFragment(Fragment fragment, int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (fragment != null) {
            // Replace current fragment by this new one
            //ft.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_in_right, R.anim.enter_from_right, R.anim.exit_in_left);
            ft.addToBackStack(fragment.getClass().getName());
            ft.replace(R.id.main_content_fragment, fragment, position + "");
            ft.commit();
        }

    }



Call this method like this:
FragmentOne FragmentOne = new FragmentOne();
initFragment(FragmentOne, position);