I have a \"Activity\" class code which I want to copy into \"Fragment\" class but unaware of Fragment structure, can someone help me to do that? Below are my two classes :
copy your activity's onCreate
code into onCreateView
of Fragment
.
in fragment you have to use layoutView
to get views instances.
like your below code to get button.
Button myButton = (Button) findViewById(R.id.findSelected);
would be converted into
Button myButton = (Button)layoutView.findViewById(R.id.findSelected);
you can declare layoutView as a class variable instead of local variable in onCreateView to make it accessible in whole fragment.
View layoutView; // making it accessible
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
layoutView = inflater.inflate(R.layout.activity_main, container, false);
and do not forget to return layoutView
instance from onCreateView
.
above suggestion are basics, now post question for specific requirement/issue, to get more helpful answer.
Edit instead of this use getActivity() to get context instance.
like in button1 = new RadioButton(this)
you should use
button1 = new RadioButton(**getActivity()**);
reason for above is, in activity this gives you instance of context as Activity is sub class of Context, but in fragment this can not give you access of the same,hence you would need to use getActivity() or getActivity().getBaseContext() to get context instance where required.