how to change fragment on button click navigation drawer

how to change fragment on button click navigation drawer

To change a fragment on a button click in a navigation drawer in Android, you can use the FragmentTransaction and FragmentManager classes.

Here's an example of how you might do this in an activity:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new MyFragment();
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.fragment_container, fragment);
                transaction.commit();
            }
        });
    }
}
So‮.www:ecru‬lautturi.com

In this example, the FragmentTransaction class is used to replace the current fragment with a new fragment when the button is clicked. The replace method is used to replace the fragment in the specified container (in this case, a view with the ID R.id.fragment_container).

You can use this approach to change the fragment in the navigation drawer as desired.

Created Time:2017-11-01 12:05:13  Author:lautturi