Android 从片段内部替换片段
我在网上读到,要调用另一个片段,要使用框架布局,需要创建一个与活动对话的界面,当按钮单击界面内的函数时,活动中定义的函数会用另一个片段替换片段,而不是创建界面,我试着直接从碎片内部做,结果成功了。那么我为什么不应该这样做呢Android 从片段内部替换片段,android,android-fragments,Android,Android Fragments,我在网上读到,要调用另一个片段,要使用框架布局,需要创建一个与活动对话的界面,当按钮单击界面内的函数时,活动中定义的函数会用另一个片段替换片段,而不是创建界面,我试着直接从碎片内部做,结果成功了。那么我为什么不应该这样做呢 import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTr
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentOne extends Fragment {
public FragmentOne() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_one, container, false);
Button btnONe = view.findViewById(R.id.btnOne);
btnONe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonPressed();
}
});
return view;
}
public void onButtonPressed() {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, new FragmentTwo("Femin Dharamshi did it!"));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
片段是活动的一部分,正如谷歌在Android开发者文档中所述,片段应该通过其父活动托管。 您可以参考此链接:-
您应该调用
getFragmentManager().beginTransaction().replace(int-id,Fragment-fr.commit()代码>在onViewCreated()
方法中,而不是onCreateView()
方法中
只需将onCreateView()
中的代码移动到onViewCreated()
方法中