主要活动OnCreate在方法之后被调用?

时间:2014-11-09 18:16:18

标签: java android android-fragments navigation-drawer

我有应该首先加载的主要活动,如果要启动新的活动/片段,则应选择抽屉项目,但由于某种原因,在主要活动创建之前调用抽屉项目方法甚至发生创建的抽屉项目被选中...基本上不确定为什么它一直让我直接进入profileactivity。

以下是主要活动代码:

public class MainActivity extends FragmentActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    //Starter fragment
    private StarterFragment starterFragment;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    //Session
    private SessionManager sessionM;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(Constants.DEBUG, "IN MAIN ACTIVITY (LOADED)");
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        //set default page to open home page
        onNavigationDrawerItemSelected(1);

    }


    private void onSessionStateChange(Session session, SessionState state, Exception exception) {

        //user is authenticated
        if (state.isOpened()) {
            Log.i("Main", "Logged in...");

            //user is not authenticated
        } else if (state.isClosed()) {
            sessionM.logoutUser();
            Log.i("Main", "Logged out...");
        }
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {

        //to switch between fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                Log.d(Constants.DEBUG, "GOING TO PROFILE ACTIVITY");
                takeToProfileActivity();
                break;
            case 1:
                fragment = new HomeFragment();
                break;

            case 2:
                fragment = new MessagesFragment();
                break;
            case 3:
                share();
                break;
            case 4:
                fragment = new SettingsFragment();
                break;
        }

        String ARG_SECTION_NUMBER = "section_number";

    if(fragment != null) {


        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position);
        fragment.setArguments(args);

        // update the main content by replacing fragments
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
    } else {
        Log.d("Error creating fragment", "Check fragment null Main Activity");
    }
    }

    public void takeToProfileActivity() {
        // user redirect to edit profile activity
        Intent profileActivity = new Intent(this, ProfileActivity.class);
        // Closing all the Activities
        profileActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        profileActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring add item
        startActivity(profileActivity);
    }

    public void onSectionAttached(int number) {


        switch (number) {
            case 0:
                mTitle = getString(R.string.title_section1);
                break;
            case 1:
                mTitle = getString(R.string.title_section2);
                break;

            case 2:
                mTitle = getString(R.string.title_section3);
                break;
            case 3:

                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
        }
    }


    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {

            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }


    @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();


        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static Fragment newInstance(int sectionNumber) {

            Fragment notUsed = null;
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            notUsed.setArguments(args);
            return notUsed;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

    private boolean checkInternet() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

    }

}

个人资料活动:

Public class ProfileActivity extends Activity{
    private SessionManager session;

    private ActionBar actionBar;
    private TextView firstName, age, status;
    private String firstSess, ageSess, statusSess;

    //TODO
    //PICTURE VIEW PAGER
    private int numPages;
    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

    //Need edit profile icon not submit for menu
    //how to make a viewpager with pictures


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


        setContentView(R.layout.activity_profile);

        //set back button
        // get action bar
        actionBar = getActionBar();

        // Enabling Up / Back navigation
        actionBar.setDisplayHomeAsUpEnabled(true);


        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);



        session = new SessionManager(this);

        firstName = (TextView) findViewById(R.id.firstName);
        age = (TextView) findViewById(R.id.age);
        status = (TextView) findViewById(R.id.status);

        firstSess = session.getUserDetails().get(SessionManager.KEY_NAME);
        ageSess = session.getUserDetails().get(SessionManager.KEY_AGE);
        statusSess = session.getUserDetails().get(SessionManager.KEY_STATUS);

        //for view pager picture count
        numPages = session.getUserPictures().size();
        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ImagePagerAdapter(getFragmentManager(), numPages);
        mPager.setAdapter(mPagerAdapter);
        mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When changing pages, reset the action bar actions since they are dependent
                // on which page is currently active. An alternative approach is to have each
                // fragment expose actions itself (rather than the activity exposing actions),
                // but for simplicity, the activity provides the actions in this sample.
                invalidateOptionsMenu();
            }
        });

        firstName.setText(firstSess);
        age.setText(ageSess);
        status.setText(statusSess);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.profile, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_edit:
                editProfile();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }




    private void editProfile() {

        // user redirect to edit profile activity
        Intent editProfileActivity = new Intent(this, EditProfileActivity.class);
        // Closing all the Activities
        editProfileActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        editProfileActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring add item
        startActivity(editProfileActivity);
    }

}

清单文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.l" >


    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <!-- for google cloud messaging -->
    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!--
     Creates a custom permission so only this app can receive its messages.

     NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
           where PACKAGE is the application's package name.
    -->
    <permission android:name="com.example.lior.winklio.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission
        android:name="com.google.android.c2dm.permission.RECEIVE" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <!--google play services-->

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
       WakefulBroadcastReceiver that will receive intents from GCM
       services and hand them to the custom IntentService.

       The com.google.android.c2dm.permission.SEND permission is necessary
       so only GCM services can send data messages for the app.
     -->
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.lior.winklio" />
            </intent-filter>
        </receiver>
        <service android:name=".GcmIntentService" />




        <activity
            android:name="com.example.lior.winklio.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



        <activity
            android:name=".ProfileActivity"
            android:label="Winklio"
            android:parentActivityName=".MainActivity" >

        </activity>

        <activity
            android:name=".EditProfileActivity"
            android:label="Winklio"
            android:parentActivityName=".ProfileActivity" >

        </activity>


    </application>



</manifest>

如果需要其他任何内容,请告诉我,此行Log.d(Constants.DEBUG,“IN MAIN ACTIVITY(LOADED)”);在此行之后调用Log.d(Constants.DEBUG,“Go to to PROFILE ACTIVITY”); ...当我将homeFragment作为第一个加载时,Profile Activity立即加载...同样,后退按钮(主页按钮)只是重新加载配置文件活动而不是返回主活动< / p>

0 个答案:

没有答案