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

 局外人2502854057 发布于 2023-02-13 17:35

我有一个场景,片段在其布局中有自定义视图(通过扩展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;

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

}

myFragmentview.xml

    

公共类CustomView扩展View {

private MyActivity context; 

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

// 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;
        }

}

}

1 个回答
  • 好.用你自己的话说:

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

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

    context.getFragmentManager().findFragmentByTag("tag_of_frag_you_are_trying_to_access");
    

    HTH.

    2023-02-13 17:37 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有