I have a scenario in which a fragment has its own view (by extending the View class) inside its layout. The user view must access some fragment methods. But I can not get the link to the fragment inside the user view. Also, I cannot access the fragment from the user view (which is a child of the fragment)
According to the android fragments: we get the context inside the view constructors. This context is an example of activity. But there is no way to get a link to the fragment on which the user view is placed.
Please let me know how to access the fragment inside the user view.
EDIT:
Adding code to better understand my problem:
MyFragment.java
public class MyFragment extends 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
<com.test.CustomView android:id="@+id/myCustomView" android:layout_width="fill_parent" android:layout_height="40dip" layout_weight="1" />
public class CustomView extends View {
private MyActivity context; 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.
}
public EasCalWeekViewHeader1(Context context, AttributeSet attrs) { super(context,attrs); this.context = (MyActivity) context; } }
}
android android-fragments android-custom-view
Manish
source share