在自定义视图中访问片段引用

Man*_*ish 12 android android-custom-view android-fragments

我有一个场景,片段在其布局中有自定义视图(通过扩展View类).自定义视图必须访问片段的某些方法.但是我无法在自定义视图中获得片段引用.此外,我无法从自定义视图(这是片段的子级)访问片段的任何方式

根据android片段:我们在视图的构造函数中获取上下文.此上下文是活动的实例.但是没有办法获得托管customview的片段的引用.

请让我知道如何访问自定义视图中的片段.

编辑:

添加代码以更好地理解我的问题:

MyFragment .java

公共类MyFragment扩展Fragment {

int selectedOptionIndex;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//get value of selectedOptionIndex from bundle and save it to this.selectedOptionIndex;

}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
this.activity = activity;

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.myFragmentview, container, false);
    return view;
Run Code Online (Sandbox Code Playgroud)

//i can access views from fragment, but not vice versa. }

}

myFragmentview.xml

    <com.test.CustomView
                android:id="@+id/myCustomView" android:layout_width="fill_parent"
                android:layout_height="40dip"  layout_weight="1"
                  />
Run Code Online (Sandbox Code Playgroud)

公共类CustomView扩展View {

private MyActivity context; 

/** Default Constructor */
public EasCalWeekViewHeader1(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
        this.context = (MyActivity) context;
Run Code Online (Sandbox Code Playgroud)

// Now using context, we can access activity insatnce inside this customView and can call any method of activity instance. //But we cannot do this for fragments. There is not way to access parent fragment at this point. I cannot access selectedOptionIndex and use it to set in this view. //if view can access the parent activty, then it should also have an access to parent fragment.
}

/** Default Constructor */
public EasCalWeekViewHeader1(Context context, AttributeSet attrs) {
    super(context,attrs);
            this.context = (MyActivity) context;
        }

}
Run Code Online (Sandbox Code Playgroud)

}

VJ *_*ons 9

好.用你自己的话说:

根据android片段:我们在视图的构造函数中获取上下文.此上下文是活动的实例.但是没有办法获得托管customview的片段的引用.

所以,上下文是活动的实例,对吧?现在从这个活动上下文中,我相信你可以获得对你的片段的引用,如果你已经分别使用findFragmentByTag(String tag)和提供了一个字符串标签名称或id findFragmentById(int id).

context.getFragmentManager().findFragmentByTag("tag_of_frag_you_are_trying_to_access");
Run Code Online (Sandbox Code Playgroud)

HTH.


Mic*_*ier 8

调用FragmentManager.findFragment(this)this您的自定义视图在哪里。

或者,如果您使用 Kotlin 的 Fragment 库androidx.fragment:fragment-ktx,则可以View.findFragment()在视图中使用扩展函数。

它被定义为:

fun <F : Fragment> View.findFragment(): F = FragmentManager.findFragment(this)
Run Code Online (Sandbox Code Playgroud)

从文档:

此方法将定位与此视图关联的 Fragment。这是为 Fragment.onCreateView 及其子项返回的视图自动填充的。