如何从膨胀的布局中找到自定义片段?

时间:2018-11-19 06:47:27

标签: android

我有一个膨胀的布局自定义片段,如何访问它? 膨胀后,我尝试了许多方法,但没有一个起作用:

  1. getTransitionManager().findFragmentById(id_xxxxx)返回null;
  2. getChildAt(x),获取视图,但无法转换为片段;
  3. 我试图以编程方式创建一个新的片段,并在膨胀视图中添加到一个容器中,但是该应用崩溃了,提示“找不到片段fff的ID xxx的视图”

代码,我想找到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>

2 个答案:

答案 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");