Android:将片段链接到活动

时间:2016-05-26 13:54:48

标签: android facebook android-fragments

我有以下片段:

public class LoginFragment extends Fragment  {

private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private static final String TAG = "LoginFragment";

private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Log.d(TAG, "onSuccess");
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        mTextDetails.setText(constructWelcomeMessage(profile));

    }


    @Override
    public void onCancel() {
        Log.d(TAG, "onCancel");
    }

    @Override
    public void onError(FacebookException e) {
        Log.d(TAG, "onError " + e);
    }
};


public LoginFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();
    setupTokenTracker();
    setupProfileTracker();

    mTokenTracker.startTracking();
    mProfileTracker.startTracking();
}


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

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    setupTextDetails(view);
    setupLoginButton(view);
}

@Override
public void onResume() {
    super.onResume();
    Profile profile = Profile.getCurrentProfile();
    mTextDetails.setText(constructWelcomeMessage(profile));
}

@Override
public void onStop() {
    super.onStop();
    mTokenTracker.stopTracking();
    mProfileTracker.stopTracking();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

private void setupTextDetails(View view) {
    mTextDetails = (TextView) view.findViewById(R.id.text_details);
}

private void setupTokenTracker() {
    mTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
            Log.d(TAG, "" + currentAccessToken);
        }
    };
}

private void setupProfileTracker() {
    mProfileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
            Log.d(TAG, "" + currentProfile);
            mTextDetails.setText(constructWelcomeMessage(currentProfile));
        }
    };
}

private void setupLoginButton(View view) {
    LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
    mButtonLogin.setFragment(this);
    mButtonLogin.setCompoundDrawables(null, null, null, null);
    mButtonLogin.setReadPermissions("user_friends");
    mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}

private String constructWelcomeMessage(Profile profile) {
    StringBuffer stringBuffer = new StringBuffer();
    if (profile != null) {
        stringBuffer.append("Welcome " + profile.getName());
    }
    return stringBuffer.toString();
}
}

以及以下MainActivity.class:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private ListAdapter listAdapter;

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



    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

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

    // Add sample data to event list.
    ListView listView = (ListView) findViewById(R.id.listView);
    listAdapter = TestData.getEventListAdapter(this);
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO: Navigate to event detail page.
        }
    });


}


@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.main2, 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) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camara) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

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

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

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

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

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

AndroidManifest

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xx.xx.xx" >
    <uses-permission android:name="android.permission.INTERNET"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
            "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"
        android:label="@string/app_name" />

    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>

    <activity
        android:name=".EventCreate"
        android:parentActivityName=".MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".EventCreate" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>

</application>
</manifest>

正如我所读到的,在Android Manifest中我无法添加片段。所以我试图将我的LoginFragment类用作Launcher,因为我希望应用程序首先使用Facebook登录按钮。不知何故,我必须使用片段管理器,但我不知道如何。

有人可以证明我如何解决这个案子吗?

3 个答案:

答案 0 :(得分:0)

添加LoginActivity以保存LoginFragment,如果用户成功登录,则继续执行MainActivity。

public static class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.login_activity_layout);

        LoginFragment loginFragment = new LoginFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.your_container, loginFragment).commit();

    }
}

login_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/your_container"
    android:orientation="horizontal">

</LinearLayout>

在您的LoginFragment中,通过意图启动您的MainActivity。

private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Log.d(TAG, "onSuccess");
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        mTextDetails.setText(constructWelcomeMessage(profile));

        Intent intent = new Intent(getActivity(), MainActivity.class);
        startActivity(intent);
    }


    @Override
    public void onCancel() {
        Log.d(TAG, "onCancel");
    }

    @Override
    public void onError(FacebookException e) {
        Log.d(TAG, "onError " + e);
    }
};

答案 1 :(得分:0)

您的活动没有用户界面。 为UI创建片段并执行操作。

https://developer.android.com/training/basics/fragments/creating.html

答案 2 :(得分:0)

您可以通过FragmentManager添加片段,如下所示:

getSupportFragmentManager().beginTransaction().add(R.id.your_container, yourFragment, yourTransActionTag).commit();

如果您只想将片段添加到空容器中,请使用&#34;添加(...)&#34;,如果您想要将新添加的片段替换为新片段,则可以使用&#34 ;替换()&#34;

请注意&#34; R.id.your_container&#34;在Activity的布局中引用ViewGroup。 (例如FrameLayout)。

有关详细信息,请查看FragmentTransaction