title: Accessing fragment reference inside a custom view
body: <p>I have a scenario where a Fragment has a customview(by extending View class) inside its layout. The custom view has to access some methods of the fragment. But I am not able to get fragment references inside a custom view. Also, I am not able to get anyway to access the fragment from the custom view(which is a child of the fragment)</p>
  <p>As per android-fragments: we get context inside the constructors of the views. This context is an instance of the activity. But there is no way to get the reference of the fragment which is hosting the customview.</p>
  <p>Please let me know how to access fragments inside a customview.</p>
  <p>EDIT:</p>
  <p>Adding the code for a better understanding of my problem:</p>
  <p>MyFragment .java</p>
  <pre><code>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.`
      }
      
  }
  </code></pre>
  <p>myFragmentview.xml</p>
  
  <p></p>
  <pre><code>    &lt;com.test.CustomView
                  android:id=&quot;@+id/myCustomView&quot; android:layout_width=&quot;fill_parent&quot;
                  android:layout_height=&quot;40dip&quot;  layout_weight=&quot;1&quot;
                    /&gt;
          
  </code></pre>
  
  <pre><code>public class CustomView extends View {
      
      private MyActivity context; 
      
      /** Default Constructor */
      public EasCalWeekViewHeader1(Context context, AttributeSet attrs, int defStyle) {
          super(context, attrs, defStyle);
              this.context = (MyActivity) context;
  </code></pre>
  <p><code>// Now using context, we can access the activity instance inside this customView and can call any method of activity instance. //But we cannot do this for fragments. There is no way to access the parent fragment at this point. I cannot access selectedOptionIndex and use it to set in this view. //if the view can access the parent activity, then it should also have access to the parent fragment. </code><br />
  }</p>
  <pre><code>/** Default Constructor */
  public EasCalWeekViewHeader1(Context context, AttributeSet attrs) {
      super(context,attrs);
              this.context = (MyActivity) context;
          }
      
  }
  </code></pre>
  <p>}</p>