Search code examples
androidandroid-fragmentsbuttonfragmentonclicklistener

From fragment to another fragment


For the first second I making a Android App where students can rent a room. Now I work on the login en register pages.

I have a problem with the register page. In my app there can two types of users register they are called "Student" and "Verhuurder". In the account fragment there are two buttons for the register pages. I can't get it working to the two pages..

I had so much trouble with activity and fragments...

Can anyone help me?

My code :

Account Fragment

public class AccountFragment extends Fragment implements View.OnClickListener{


public AccountFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if (MainActivity.loginId == "")
    {
        return inflater.inflate(R.layout.fragment_account, container, false);
    }

    else
    {
        return inflater.inflate(R.layout.inlog_account, container, false);
    }
}


// BUTTON
Button btnStudent = (Button) view.findViewById(R.id.btnRegisterStudent);
btnStudent.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStudent:
                //what to put here
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fragment_container, new AccountFragmentStudent());
                ft.commit();
                break;
        }
    }
});
}

XML Account fragment

    <Button
        android:id="@+id/btnRegisterStudent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:text="Student op zoek naar een kamer"
        android:background="@color/colorPrimary"
        android:onClick="StudentRegister"/>

MainActivity

   public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, Callback<LoginResults> {

    private EditText emailInput;
    private EditText passwordInput;
    private HomeFragment fragment;

    public static String loginId = "";
    public static String loginSecret = "";

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

    HomeFragment fragment = new HomeFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.fragment_container, fragment);
    fragmentTransaction.commit();

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

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

public void Login(View v) {
    emailInput = (EditText) findViewById(R.id.email);
    passwordInput = (EditText) findViewById(R.id.password);
    String email = emailInput.getText().toString();
    String password = passwordInput.getText().toString();
    doLogin(email, password);
}

public void onResponse(Response<LoginResults> response) {
    if (response.isSuccess() && response.body() != null) {

        loginId = response.body().clientId;
        loginSecret = response.body().clientSecret;
        fragment.setLoginToken1(loginId);
        fragment.setLoginToken2(loginSecret);

        new AlertDialog.Builder(MainActivity.this)
                .setTitle("Gelukt")
                .setMessage("U bent ingelogd")
                .setCancelable(false)
                .setPositiveButton("oke", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create().show();

        // Create fragment and give it an argument specifying the article it should show
        InlogAccountFragment newFragment = new InlogAccountFragment();
        Bundle args = new Bundle();
        newFragment.setArguments(args);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();


        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);


        transaction.commit();

    }
    else

        new AlertDialog.Builder(MainActivity.this)
                .setTitle("Mislukt")
                .setMessage("Uw inloggegevens zijn incorrect")
                .setCancelable(false)
                .setPositiveButton("oke", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create().show();
    {

    }
}

public void onFailure(Throwable t) {

    new AlertDialog.Builder(MainActivity.this)
            .setTitle("Er is iets fouts gegaan")
            .setMessage("Probeer opnieuw")
            .setCancelable(false)
            .setPositiveButton("oke", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).create().show();



}
public void doLogin(String email, String password){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("BLABLA")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    Login service = retrofit.create(Login.class);

    service.loginResults(
            email,
            password

    ).enqueue(this);
}

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

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

        HomeFragment fragment = new HomeFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

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

        FavoriteFragment fragment = new FavoriteFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

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

        MessageFragment fragment = new MessageFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

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

        AccountFragment fragment = new AccountFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

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

        SettingsFragment fragment = new SettingsFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();


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


}

Solution

  • I generally try to keep my fragments light and decoupled, and delegate heavy lifting (particularly interaction with other fragments) to the activity which is using them. You might like to try the following approach:

    Try adding a listener interface to your AccountFragment - something like this:

    public interface Listener {
        void onStudentRegistrationSelected();
        void onVerhuurderRegistrationSelected();
    }
    

    You'll also need to add:

    // Member declaration at the top of the fragment class
    private Listener mListener;
    
    @Override public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mListener = (Listener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement " +
                    Listener.class.getSimpleName() + ".");
        }
    }
    

    This will set the activity which is using the fragment as the listener.

    Then, set up the on click handler of the appropriate buttons in AccountFragment to call the appropriate method on the listener. Something like this:

    view.findViewById(R.id.btnRegisterStudent).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mListener.onStudentRegistrationSelected();
        }
    }
    

    Back in MainActivity, implement the AccountFragment.Listener interface, override the methods of the listener, and create and commit the appropriate registration fragment in each of the listener method overrides - for example, onStudentRegistrationSelected() would display the AccountFragmentStudent fragment. Also, if you add this to the fragment backstack, then the user will be returned to the AccountFragment if they hit the back button while on the AccountFragmentStudent, which is a nice piece of UX.

    Hope that helps!