Amir2511
Amir2511

Reputation: 37

Show the toast before fragment start

I'm beginner in Android and am trying to write a simple application. When into fragment click on button start other fragment, for that purpose:

@Override
public void onClick(View v) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            secondFragment.removeAllViews();
            transaction.replace(R.id.secondFragment, new DashBoardFragment());
            transaction.commit();
        }
    });
}

but after other fragment start show the Hello Toast, but I want show before fragment start.

Upvotes: 0

Views: 70

Answers (1)

Santanu Sur
Santanu Sur

Reputation: 11477

Try this in onClick after toasting :-

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        secondFragment.removeAllViews();
        transaction.replace(R.id.secondFragment, new DashBoardFragment());
        transaction.commit();
    }
}, Toast.LENGTH_SHORT);

Your fragment transaction will take place after 1500 ms ( hence your toast message would shoot up before transaction takes place )

Your full on click method...

@Override
public void onClick(View v) {
    Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            secondFragment.removeAllViews();
            transaction.replace(R.id.secondFragment, new DashBoardFragment());
            transaction.commit();    
        }  
    }, Toast.LENGTH_SHORT);              
}

Upvotes: 3

Related Questions