我有一个场景,片段在其布局中有自定义视图(通过扩展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; } }
}
好.用你自己的话说:
根据android片段:我们在视图的构造函数中获取上下文.此上下文是活动的实例.但是没有办法获得托管customview的片段的引用.
所以,上下文是活动的实例,对吧?现在从这个活动上下文中,我相信你可以获得对你的片段的引用,如果你已经分别使用findFragmentByTag(String tag)
和提供了一个字符串标签名称或id findFragmentById(int id)
.
context.getFragmentManager().findFragmentByTag("tag_of_frag_you_are_trying_to_access");
HTH.