What you want to do is precisely the goal of the Fragments
A Fragment represents a behavior or part of the interface
of user in an Activity.
Basically to convert a Activity
to Fragment
you need:
- Your class should extend the class
Fragment
instead of Activity
or AppCompatActivity
, etc ...
- Use
onCreateView()
instead of onCreate()
.
- Instead of using findViewById () to find the references of the views you should use
getView().findViewById()
As an example I show you a Activity
:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class ActivityLeoaica extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Elenasys was here!");
}
}
and now the same Activity
converted to Fragment
:
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentLeoaica extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
TextView textView = (TextView) getView().findViewById(R.id.textView);
textView.setText("Elenasys was here!");
return view;
}
}
A Fragment
can be considered a piece of UI, for example in the following image you can see a Fragment
that is a List and another that shows content related to a list, both Fragments
contained in a Activity
:
If you want to add a piece of UI with a map then you would use a MapFragment , this is an example of an application:
I suggest you take the example of this tutorial so that you understand how to handle the Fragments
:
Using Snippets in an Android Application