【发布时间】:2013-12-16 12:24:42
【问题描述】:
我有一个场景,片段在其布局中有一个自定义视图(通过扩展视图类)。自定义视图必须访问片段的一些方法。但我无法在自定义视图中获取片段引用。此外,我无法从自定义视图(片段的子视图)访问片段
根据 android 片段:我们在视图的构造函数中获取上下文。此上下文是活动的实例。但是无法获取托管 customview 的片段的引用。
请告诉我如何访问自定义视图中的片段。
编辑:
添加代码以便更好地理解我的问题:
MyFragment .java
公共类 MyFragment 扩展片段 {
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
<com.test.CustomView
android:id="@+id/myCustomView" android:layout_width="fill_parent"
android:layout_height="40dip" layout_weight="1"
/>
公共类 CustomView 扩展视图 {
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 android-fragments android-custom-view