Amit Pal Amit Pal - 1 month ago 5
Android Question

Not able to call android annotation methods in fragment?

I am using

Android annotation
in inflate the
Fragment
:

@EFragment(R.layout.fragment_sample)
public class SampleFragment extends Fragment {
public static SampleFragment newInstance(Context context) {
mContext = context;
SampleFragment samplefragment = new SampleFragment_();
return samplefragment;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}

@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
}

@AfterViews
public void afterViewsCreated(){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
}}


I am invoking the instance of above fragment class from an
Activity
:

SampleFragment.newInstance(getApplicationContext());


After enabling
debug
point in the code. Code flow is only limited to
newInstance
method. Debugger is not even going to
onActivityCreated()
,
onCreate()
and
afterViewsCreated()
.
@AfterViews
needs to be get called.

Why is this so happening?

Answer

All you appear to be doing is creating an instance of the fragment. You don't appear to be actually calling to the FragmentManager to add()/replace() this new instance.

Try:

Fragment fragment = SampleFragment.newInstance(getApplicationContext());

getFragmentManager.beginTransation()
    .add(<ID RES>, fragment, <FRAGMENT TAG>)
    .commit();

Where ID RES is your resource id and FRAGMENT TAG is your fragment tag, if required.

See this post for more info on using FragmentManager.