我有一个膨胀的布局自定义片段,如何访问它? 膨胀后,我尝试了许多方法,但没有一个起作用:
getTransitionManager().findFragmentById(id_xxxxx)
返回null; getChildAt(x)
,获取视图,但无法转换为片段; 代码,我想找到ReportCalenderFragment
并按住:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
LayoutInflater inflater = LayoutInflater.from(getActivity());
mCalendar = inflater.inflate(R.layout.dlg_choose_report, null);
ConstraintLayout ly = (ConstraintLayout)mCalendar;
RelativeLayout rly = (RelativeLayout)ly.getChildAt(0);
LinearLayout lly = (LinearLayout)rly.getChildAt(0);
View v = (View)lly.getChildAt(0);
//lly.setId(R.id.report_calendar_con);
//ReportCalenderFragment frag = new ReportCalenderFragment();
//FragmentTransaction fragTrans = getChildFragmentManager().beginTransaction();
//fragTrans.add(R.id.report_calendar_con, frag);
//fragTrans.commit();
//ReportCalenderFragment frag = (ReportCalenderFragment)lly.getChildAt(0);
...
}
XML ConstraintLayout
被此文本编辑器过滤:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/report_calendar_con"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#000"
android:orientation="vertical">
<fragment
android:id="@+id/frag_calendar_rp"
android:name="package.fragments.ReportCalenderFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:0)
喜欢这个:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ReportCalenderFragment fragment= (ReportCalenderFragment) getSupportFragmentManager().findFragmentById(R.id.frag_calendar_rp);//this method
Log.e(getClass().getSimpleName(),fragment.toString());
}
答案 1 :(得分:0)
尝试
ReportCalenderFragment frag = (ReportCalenderFragment) getParentFragment().getFragmentManager().findFragmentById(R.id.frag_calendar_rp);
如果您在对话框中(另一个片段之内)使用ReportCalenderFragment
显示对话框时,您应使用父片段中的ChildFragmentmanager
MyDialogFragment dialogFragment = new MyDialogFragment();
dialogFragment.show(getChildFragmentManager(), "dialog");