如何从一个片段移动到新片段?

时间:2017-04-06 14:31:54

标签: android android-fragments

我试图通过点击按钮移动到另一个片段。名为FirstFragment的当前片段和名为AttendanceFragment的目标片段。当我运行应用程序时,它只是崩溃了。 这是当前片段的代码

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


/**
 * A simple {@link Fragment} subclass.
*/
public class FirstFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_first, container, false);

    Button btn1 = (Button) v.findViewById(R.id.btn1);
    btn1.setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    AttendanceFragment fragment = new AttendanceFragment();
                    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.register_attendance, fragment);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }
    );
    return v;
}

}

2 个答案:

答案 0 :(得分:3)

  

制作界面。

public interface FragmentChangeListener{
    public void replaceFragment(Fragment fragment); 
}
  

使用此界面实现您的父活动。

public class MainActivity extends Activity implements FragmentChangeListener {
         @Override
         public void replaceFragment(Fragment fragment) {
            FragmentManager fragmentManager = getSupportFragmentManager();;     
            FragmentTransaction fragmentTransaction = 
            fragmentManager.beginTransaction();
            fragmentTransaction.replace(mContainerId, fragment);
            fragmentTransaction.addToBackStack(fragment.toString());
            fragmentTransaction.commit();   
    }
}
  

从像这样的片段中调用此方法。

//In your fragment - call this method from onClickListener
public void showOtherFragment(){
       Fragment fragment=new NewFragmentName();
       FragmentChangeListener listener = (FragmentChangeListener)getActivity();
       listener.replaceFragment(fragment); 
}

答案 1 :(得分:0)

请阅读Communicating with other Fragments

在那里,您可以找到由@Sanjog Shrestha发布的优雅版解决方案。您应该在onAttach(Activity activity)注册回调并在onDetach()取消注册。最好确保Activity实现自己定义的接口。