DAVIDBALAS1 DAVIDBALAS1 - 3 months ago 30
Android Question

Button setOnClickListener onCreateView() or onActivityCreated() in Fragment

by this answer
I can't understand where to put my

onClickListener()
- inside
onCreateView()
or inside
onActivityCreated()
, below codes describe it better:

CODE A: (Setting Button click listener inside
onActivityCreated()
)

private FloatingActionButton bt;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// do something.
}
});
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
bt = (FloatingActionButton) v.findViewById(R.id.fab);
return v;
}


CODE B: (Setting Button click listener inside
onCreateView()
)

private FloatingActionButton bt;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
bt = (FloatingActionButton) v.findViewById(R.id.fab);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// do something.
}
});
return v;
}


I may have not understood which code is better because of my poor English, anyway, thank you all :)

Answer

Both will have no effect as far as I know. Once the view is inflated you can put it anywhere either in onCreateView() or in onActivityCreated().

After all, for binding views and setting click listeners, onViewCreated() is a better candidate though, as it will be called immediately after onCreateView. It clearly suggests that your view has been inflated.

There is no specific reason or rule for it. Google itself doesn't care much about it. As a rule of thumb, you can put it anywhere you want once the view is inflated.