简体   繁体   中英

Correct way to setup onClickListener with Fragments

This is my first time working with fragments. I'm implementing a facebook login. When I add the piece of code for the fragment

            /* FACEBOOK FRAGMENT SETUP */
            if (savedInstanceState == null) {
                // Add the fragment on initial activity setup
                mainFragment = new MainFragment();
                getSupportFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, mainFragment)
                .commit();
            } else {
                // Or set the fragment from restored state info
                mainFragment = (MainFragment) getSupportFragmentManager()
                .findFragmentById(android.R.id.content);
            }

then none of the onClickListeners for my buttons or text views work. I'm not sure why this is happening. Can anyone shed light on this?

Main Activity Code

public class ActivityLogin extends FragmentActivity {
     // label to display gcm messages
    TextView lblMessage;

    // Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;




    private EditText edt_username, edt_password;
    public String gcm_id, un, pw, tab;
    public ProgressDialog pdialog;
    static int count = 0;
    public String gcm_regid;

    ConnectionDetector cd;
    AlertDialogManager alert = new AlertDialogManager();
    SharedPreferences sp1;
    GPSTracker gpstracker;


    RequestQueue queue;

    //FB FRAGMENT
    private MainFragment mainFragment;

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





        Intent in = getIntent();
        tab = in.getStringExtra("tab");
        queue = Volley.newRequestQueue(this);

        //Check for saved credentials.
        sp1=getSharedPreferences("Login",MODE_PRIVATE);
        un = sp1.getString("un", "");
        pw = sp1.getString("pw", "");

        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
        gpstracker = new GPSTracker(getApplicationContext());

        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        //GCMRegistrar.checkManifest(this);


        cd = new ConnectionDetector(getApplicationContext());

        //registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
        final String regId = GCMRegistrar.getRegistrationId(this);

        // Check if regid already presents
        if (regId.equals("")) {
            // Registration is not present, register now with GCM           
            GCMRegistrar.register(this, SENDER_ID);
            gcm_id=GCMRegistrar.getRegistrationId(this);
        } else {
            gcm_id=regId;
            // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.              
                Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
            }
        }


        /*if(un==""){*/
            setContentView(R.layout.login_layout);



            Button login = (Button) findViewById(R.id.btn_login);
            /* init EditText */
            edt_username = (EditText) findViewById(R.id.edt_userNameLogin);
            edt_password = (EditText) findViewById(R.id.edt_PasswordLogin);


            login.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (edt_username.getText().toString().equalsIgnoreCase("")) {

                        alert.showAlertDialog(ActivityLogin.this, "KpFun alert!",
                                "Username no empty!", false);
                        edt_username.requestFocus();
                        return;
                    }
                    if (edt_password.getText().toString().equalsIgnoreCase("")) {
                        alert.showAlertDialog(ActivityLogin.this, "KpFun alert!",
                                "Password no empty!", false);
                        edt_password.requestFocus();
                        return;
                    }
                    if (!cd.isConnectingToInternet()) {
                        alert.showAlertDialog(ActivityLogin.this, "KpFun alert!",
                                "No network, Please check your data connection!",
                                false);
                        return;
                    }

                    Login();

                }
            });

            TextView backLink = (TextView) findViewById(R.id.tv_Back);
            backLink.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent inRegister = new Intent(ActivityLogin.this,
                            SplashScreen.class);
                    startActivity(inRegister);
                    finish();

                }
            });


        /*}else{
            Login();

        }*/

             /* FACEBOOK FRAGMENT SETUP */
            if (savedInstanceState == null) {
                // Add the fragment on initial activity setup
                mainFragment = new MainFragment();
                getSupportFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, mainFragment)
                .commit();
            } else {
                // Or set the fragment from restored state info
                mainFragment = (MainFragment) getSupportFragmentManager()
                .findFragmentById(android.R.id.content);
            }



            if(!un.equals("")){
                Login();
            }



    }
    /* MORE STUFF TAKEN OUT */

FRAGMENT CODE

package com.kpfunusa1;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.facebook.Response;
import com.facebook.Request;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;


public class MainFragment extends Fragment {
    private static final String TAG = "MainFragment";
    private UiLifecycleHelper uiHelper;


    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(getActivity(), callback); 
         uiHelper.onCreate(savedInstanceState);


    }



    @Override
    public View onCreateView(LayoutInflater inflater, 
            ViewGroup container, 
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_layout, container, false);

        LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday", "user_location", "user_website", "user_likes", "user_status"));

        return view;
    }


    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };


    private void onSessionStateChange(Session session, SessionState state, Exception exception) 
     {
        if (state.isOpened()) 
        {
            Log.i("facebook", "Logged in...");
            Request.newMeRequest(session, new Request.GraphUserCallback() 
            {

                @Override
                public void onCompleted(GraphUser user, Response response) 
                {

                    if(user!=null)
                    {
                      String test=user.getName();
                      test =user.getProperty("email")+"";
                      test=(user.getProperty("gender")+"");
                      test=(user.getId()+"");
                      test=user.getBirthday();
                      test=user.getUsername();
                      test=user.getId();
                    }
                    else
                    {
                        String test=("its null");
                        test=(response.getError().getErrorMessage());
                    }
                }
            }).executeAsync();

        } 
        else if (state.isClosed()) 
        {
            Log.i("facebook", "Logged out...");
        }
    }


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

        // For scenarios where the main activity is launched and user
        // session is not null, the session state change notification
        // may not be triggered. Trigger it if it's open/closed.
        Session session = Session.getActiveSession();
        if (session != null &&
               (session.isOpened() || session.isClosed()) ) {
            onSessionStateChange(session, session.getState(), null);
        }

        uiHelper.onResume();
    }

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

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

}

UiLifecycleHelper should be created and called all on*(Create/Resume etc) methods in Login activity, because onActivityResult in Fragment never be called.

And you should implement UI(login btn etc) only in fragment code. In Activity.setContentView you should set layout where defined login fragment.

Have you tried import the correct library in your Main Activity?

try import:

import android.support.v4.app.FragmentActivity;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM