What can I remove to make an empty fragment look “cleaner”
When I create an empty fragment on Android Studio it generates the following code:
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link TestFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link TestFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TestFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public TestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TestFragment.
*/
// TODO: Rename and change types and number of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
It's quite complicated for an empty fragment. What is the purpose of each part that's created, and can I remove some of the code to make it "simpler"?
What's not necessary? Because when I create an empty activity it's much more "clean"
android
add a comment |
When I create an empty fragment on Android Studio it generates the following code:
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link TestFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link TestFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TestFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public TestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TestFragment.
*/
// TODO: Rename and change types and number of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
It's quite complicated for an empty fragment. What is the purpose of each part that's created, and can I remove some of the code to make it "simpler"?
What's not necessary? Because when I create an empty activity it's much more "clean"
android
it's like buying a car, you may never use the boot but it's still there. I am not sure if it makes the car more complicated for the user? or would it be cleaner looking without it? Auto-generated classes tend to have minimum code necessary but surely you can get rid of the parts you don't need if it is still not simple enough for you
– Ulug Toprak
Jan 2 at 14:18
You don't need to use auto-generated fragments - you can just create a new class, have it extendFragment
and you're done.
– PPartisan
Jan 2 at 15:04
add a comment |
When I create an empty fragment on Android Studio it generates the following code:
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link TestFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link TestFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TestFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public TestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TestFragment.
*/
// TODO: Rename and change types and number of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
It's quite complicated for an empty fragment. What is the purpose of each part that's created, and can I remove some of the code to make it "simpler"?
What's not necessary? Because when I create an empty activity it's much more "clean"
android
When I create an empty fragment on Android Studio it generates the following code:
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link TestFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link TestFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TestFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public TestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TestFragment.
*/
// TODO: Rename and change types and number of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
It's quite complicated for an empty fragment. What is the purpose of each part that's created, and can I remove some of the code to make it "simpler"?
What's not necessary? Because when I create an empty activity it's much more "clean"
android
android
asked Jan 2 at 14:09
sStackersStacker
717
717
it's like buying a car, you may never use the boot but it's still there. I am not sure if it makes the car more complicated for the user? or would it be cleaner looking without it? Auto-generated classes tend to have minimum code necessary but surely you can get rid of the parts you don't need if it is still not simple enough for you
– Ulug Toprak
Jan 2 at 14:18
You don't need to use auto-generated fragments - you can just create a new class, have it extendFragment
and you're done.
– PPartisan
Jan 2 at 15:04
add a comment |
it's like buying a car, you may never use the boot but it's still there. I am not sure if it makes the car more complicated for the user? or would it be cleaner looking without it? Auto-generated classes tend to have minimum code necessary but surely you can get rid of the parts you don't need if it is still not simple enough for you
– Ulug Toprak
Jan 2 at 14:18
You don't need to use auto-generated fragments - you can just create a new class, have it extendFragment
and you're done.
– PPartisan
Jan 2 at 15:04
it's like buying a car, you may never use the boot but it's still there. I am not sure if it makes the car more complicated for the user? or would it be cleaner looking without it? Auto-generated classes tend to have minimum code necessary but surely you can get rid of the parts you don't need if it is still not simple enough for you
– Ulug Toprak
Jan 2 at 14:18
it's like buying a car, you may never use the boot but it's still there. I am not sure if it makes the car more complicated for the user? or would it be cleaner looking without it? Auto-generated classes tend to have minimum code necessary but surely you can get rid of the parts you don't need if it is still not simple enough for you
– Ulug Toprak
Jan 2 at 14:18
You don't need to use auto-generated fragments - you can just create a new class, have it extend
Fragment
and you're done.– PPartisan
Jan 2 at 15:04
You don't need to use auto-generated fragments - you can just create a new class, have it extend
Fragment
and you're done.– PPartisan
Jan 2 at 15:04
add a comment |
2 Answers
2
active
oldest
votes
can I remove some of the code to make it "simpler"? What's not necessary?
You can actually remove all of the code. The only truly necessary part is the class definition itself:
public class TestFragment extends Fragment {
}
You don't even need the "required empty public constructor", because the compiler will add that for you. You should just never specify a constructor manually (except in very narrow cases that are outside the scope of this question).
Of course, most of the time you use fragments, you're going to use them to display information to the user, in which case you need to include the onCreateView()
method:
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
This method is responsible for creating the fragment's view. You aren't required to inflate a view (you can make one by hand and return that instead), but you do have to return some non-null view if you want the user to see anything. Whatever you return from this method can be retrieved later by calling getView()
.
Note that it's perfectly valid to use a fragment with no view (e.g. a retained fragment used only as a container for long-running tasks).
Another common thing to do with fragments is use onAttach()
and onDetach()
to cast the activity hosting the fragment to some interface
. This lets the fragment class be used with multiple host activities, as long as each activity implements the interface.
public class TestFragment extends Fragment {
private MyListenerInterface mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mListener = (MyListenerInterface) context;
}
@Override
public void onDetach() {
super.onDetach();
this.mListener = null;
}
public interface MyListenerInterface {
void someMethod();
}
}
You can just cast the context directly, without the if
statement included in the generated code, because either way you're going to get a runtime exception thrown (you'll just get a ClassCastException
instead).
You can define whatever methods you need in this interface.
Finally, the generated fragment is demonstrating the newInstance()
pattern to use for "passing arguments" to the fragment. As mentioned before, you should never use a constructor with fragments, so how can you pass data to them? You can use the "arguments" Bundle
, set that to the fragment, and then later retrieve the data using getArguments()
.
Doing that all manually every time would be annoying, so you can wrap it all in a newInstance()
static factory method to make things easier:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public static TestFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mParam1 = getArguments().getString(ARG_PARAM1);
this.mParam2 = getArguments().getString(ARG_PARAM2);
}
}
With this in place, anyone who needs to create an instance of this fragment can just call
TestFragment f = TestFragment.newInstance("Hello", "world");
Instead of having to write:
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("param1", "Hello");
args.putString("param2", "world");
f.setArguments(args);
The Bundle
class can handle many different types of data; this example is using Strings but you can use ints or Lists, etc. I've removed the if
check from onCreate()
because we know that the arguments bundle will always be non-null, so the check is useless. The only way for it to not be non-null is if someone doesn't call newInstance()
, and we're much better off crashing and fixing that problem than trying to soldier on without the data we need.
You can call getArguments()
from any method, not just onCreate()
.
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
add a comment |
If your fragment is so simple you can use this instead
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
//ADD THIS
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//YOUR LOGIC
}
}
Other functions use for callbacks and share variable between fragments
This two is important
onCreateView : for inflate layout
onActivityCreated : for write logic codes
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54007823%2fwhat-can-i-remove-to-make-an-empty-fragment-look-cleaner%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
can I remove some of the code to make it "simpler"? What's not necessary?
You can actually remove all of the code. The only truly necessary part is the class definition itself:
public class TestFragment extends Fragment {
}
You don't even need the "required empty public constructor", because the compiler will add that for you. You should just never specify a constructor manually (except in very narrow cases that are outside the scope of this question).
Of course, most of the time you use fragments, you're going to use them to display information to the user, in which case you need to include the onCreateView()
method:
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
This method is responsible for creating the fragment's view. You aren't required to inflate a view (you can make one by hand and return that instead), but you do have to return some non-null view if you want the user to see anything. Whatever you return from this method can be retrieved later by calling getView()
.
Note that it's perfectly valid to use a fragment with no view (e.g. a retained fragment used only as a container for long-running tasks).
Another common thing to do with fragments is use onAttach()
and onDetach()
to cast the activity hosting the fragment to some interface
. This lets the fragment class be used with multiple host activities, as long as each activity implements the interface.
public class TestFragment extends Fragment {
private MyListenerInterface mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mListener = (MyListenerInterface) context;
}
@Override
public void onDetach() {
super.onDetach();
this.mListener = null;
}
public interface MyListenerInterface {
void someMethod();
}
}
You can just cast the context directly, without the if
statement included in the generated code, because either way you're going to get a runtime exception thrown (you'll just get a ClassCastException
instead).
You can define whatever methods you need in this interface.
Finally, the generated fragment is demonstrating the newInstance()
pattern to use for "passing arguments" to the fragment. As mentioned before, you should never use a constructor with fragments, so how can you pass data to them? You can use the "arguments" Bundle
, set that to the fragment, and then later retrieve the data using getArguments()
.
Doing that all manually every time would be annoying, so you can wrap it all in a newInstance()
static factory method to make things easier:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public static TestFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mParam1 = getArguments().getString(ARG_PARAM1);
this.mParam2 = getArguments().getString(ARG_PARAM2);
}
}
With this in place, anyone who needs to create an instance of this fragment can just call
TestFragment f = TestFragment.newInstance("Hello", "world");
Instead of having to write:
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("param1", "Hello");
args.putString("param2", "world");
f.setArguments(args);
The Bundle
class can handle many different types of data; this example is using Strings but you can use ints or Lists, etc. I've removed the if
check from onCreate()
because we know that the arguments bundle will always be non-null, so the check is useless. The only way for it to not be non-null is if someone doesn't call newInstance()
, and we're much better off crashing and fixing that problem than trying to soldier on without the data we need.
You can call getArguments()
from any method, not just onCreate()
.
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
add a comment |
can I remove some of the code to make it "simpler"? What's not necessary?
You can actually remove all of the code. The only truly necessary part is the class definition itself:
public class TestFragment extends Fragment {
}
You don't even need the "required empty public constructor", because the compiler will add that for you. You should just never specify a constructor manually (except in very narrow cases that are outside the scope of this question).
Of course, most of the time you use fragments, you're going to use them to display information to the user, in which case you need to include the onCreateView()
method:
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
This method is responsible for creating the fragment's view. You aren't required to inflate a view (you can make one by hand and return that instead), but you do have to return some non-null view if you want the user to see anything. Whatever you return from this method can be retrieved later by calling getView()
.
Note that it's perfectly valid to use a fragment with no view (e.g. a retained fragment used only as a container for long-running tasks).
Another common thing to do with fragments is use onAttach()
and onDetach()
to cast the activity hosting the fragment to some interface
. This lets the fragment class be used with multiple host activities, as long as each activity implements the interface.
public class TestFragment extends Fragment {
private MyListenerInterface mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mListener = (MyListenerInterface) context;
}
@Override
public void onDetach() {
super.onDetach();
this.mListener = null;
}
public interface MyListenerInterface {
void someMethod();
}
}
You can just cast the context directly, without the if
statement included in the generated code, because either way you're going to get a runtime exception thrown (you'll just get a ClassCastException
instead).
You can define whatever methods you need in this interface.
Finally, the generated fragment is demonstrating the newInstance()
pattern to use for "passing arguments" to the fragment. As mentioned before, you should never use a constructor with fragments, so how can you pass data to them? You can use the "arguments" Bundle
, set that to the fragment, and then later retrieve the data using getArguments()
.
Doing that all manually every time would be annoying, so you can wrap it all in a newInstance()
static factory method to make things easier:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public static TestFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mParam1 = getArguments().getString(ARG_PARAM1);
this.mParam2 = getArguments().getString(ARG_PARAM2);
}
}
With this in place, anyone who needs to create an instance of this fragment can just call
TestFragment f = TestFragment.newInstance("Hello", "world");
Instead of having to write:
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("param1", "Hello");
args.putString("param2", "world");
f.setArguments(args);
The Bundle
class can handle many different types of data; this example is using Strings but you can use ints or Lists, etc. I've removed the if
check from onCreate()
because we know that the arguments bundle will always be non-null, so the check is useless. The only way for it to not be non-null is if someone doesn't call newInstance()
, and we're much better off crashing and fixing that problem than trying to soldier on without the data we need.
You can call getArguments()
from any method, not just onCreate()
.
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
add a comment |
can I remove some of the code to make it "simpler"? What's not necessary?
You can actually remove all of the code. The only truly necessary part is the class definition itself:
public class TestFragment extends Fragment {
}
You don't even need the "required empty public constructor", because the compiler will add that for you. You should just never specify a constructor manually (except in very narrow cases that are outside the scope of this question).
Of course, most of the time you use fragments, you're going to use them to display information to the user, in which case you need to include the onCreateView()
method:
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
This method is responsible for creating the fragment's view. You aren't required to inflate a view (you can make one by hand and return that instead), but you do have to return some non-null view if you want the user to see anything. Whatever you return from this method can be retrieved later by calling getView()
.
Note that it's perfectly valid to use a fragment with no view (e.g. a retained fragment used only as a container for long-running tasks).
Another common thing to do with fragments is use onAttach()
and onDetach()
to cast the activity hosting the fragment to some interface
. This lets the fragment class be used with multiple host activities, as long as each activity implements the interface.
public class TestFragment extends Fragment {
private MyListenerInterface mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mListener = (MyListenerInterface) context;
}
@Override
public void onDetach() {
super.onDetach();
this.mListener = null;
}
public interface MyListenerInterface {
void someMethod();
}
}
You can just cast the context directly, without the if
statement included in the generated code, because either way you're going to get a runtime exception thrown (you'll just get a ClassCastException
instead).
You can define whatever methods you need in this interface.
Finally, the generated fragment is demonstrating the newInstance()
pattern to use for "passing arguments" to the fragment. As mentioned before, you should never use a constructor with fragments, so how can you pass data to them? You can use the "arguments" Bundle
, set that to the fragment, and then later retrieve the data using getArguments()
.
Doing that all manually every time would be annoying, so you can wrap it all in a newInstance()
static factory method to make things easier:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public static TestFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mParam1 = getArguments().getString(ARG_PARAM1);
this.mParam2 = getArguments().getString(ARG_PARAM2);
}
}
With this in place, anyone who needs to create an instance of this fragment can just call
TestFragment f = TestFragment.newInstance("Hello", "world");
Instead of having to write:
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("param1", "Hello");
args.putString("param2", "world");
f.setArguments(args);
The Bundle
class can handle many different types of data; this example is using Strings but you can use ints or Lists, etc. I've removed the if
check from onCreate()
because we know that the arguments bundle will always be non-null, so the check is useless. The only way for it to not be non-null is if someone doesn't call newInstance()
, and we're much better off crashing and fixing that problem than trying to soldier on without the data we need.
You can call getArguments()
from any method, not just onCreate()
.
can I remove some of the code to make it "simpler"? What's not necessary?
You can actually remove all of the code. The only truly necessary part is the class definition itself:
public class TestFragment extends Fragment {
}
You don't even need the "required empty public constructor", because the compiler will add that for you. You should just never specify a constructor manually (except in very narrow cases that are outside the scope of this question).
Of course, most of the time you use fragments, you're going to use them to display information to the user, in which case you need to include the onCreateView()
method:
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
This method is responsible for creating the fragment's view. You aren't required to inflate a view (you can make one by hand and return that instead), but you do have to return some non-null view if you want the user to see anything. Whatever you return from this method can be retrieved later by calling getView()
.
Note that it's perfectly valid to use a fragment with no view (e.g. a retained fragment used only as a container for long-running tasks).
Another common thing to do with fragments is use onAttach()
and onDetach()
to cast the activity hosting the fragment to some interface
. This lets the fragment class be used with multiple host activities, as long as each activity implements the interface.
public class TestFragment extends Fragment {
private MyListenerInterface mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mListener = (MyListenerInterface) context;
}
@Override
public void onDetach() {
super.onDetach();
this.mListener = null;
}
public interface MyListenerInterface {
void someMethod();
}
}
You can just cast the context directly, without the if
statement included in the generated code, because either way you're going to get a runtime exception thrown (you'll just get a ClassCastException
instead).
You can define whatever methods you need in this interface.
Finally, the generated fragment is demonstrating the newInstance()
pattern to use for "passing arguments" to the fragment. As mentioned before, you should never use a constructor with fragments, so how can you pass data to them? You can use the "arguments" Bundle
, set that to the fragment, and then later retrieve the data using getArguments()
.
Doing that all manually every time would be annoying, so you can wrap it all in a newInstance()
static factory method to make things easier:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public static TestFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mParam1 = getArguments().getString(ARG_PARAM1);
this.mParam2 = getArguments().getString(ARG_PARAM2);
}
}
With this in place, anyone who needs to create an instance of this fragment can just call
TestFragment f = TestFragment.newInstance("Hello", "world");
Instead of having to write:
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("param1", "Hello");
args.putString("param2", "world");
f.setArguments(args);
The Bundle
class can handle many different types of data; this example is using Strings but you can use ints or Lists, etc. I've removed the if
check from onCreate()
because we know that the arguments bundle will always be non-null, so the check is useless. The only way for it to not be non-null is if someone doesn't call newInstance()
, and we're much better off crashing and fixing that problem than trying to soldier on without the data we need.
You can call getArguments()
from any method, not just onCreate()
.
answered Jan 2 at 16:09
Ben P.Ben P.
24.8k32251
24.8k32251
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
add a comment |
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
Very in depth answer, thank you. Must admit I did not understand all myself, I'm a real novice with Android.
– sStacker
Jan 2 at 21:05
add a comment |
If your fragment is so simple you can use this instead
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
//ADD THIS
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//YOUR LOGIC
}
}
Other functions use for callbacks and share variable between fragments
This two is important
onCreateView : for inflate layout
onActivityCreated : for write logic codes
add a comment |
If your fragment is so simple you can use this instead
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
//ADD THIS
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//YOUR LOGIC
}
}
Other functions use for callbacks and share variable between fragments
This two is important
onCreateView : for inflate layout
onActivityCreated : for write logic codes
add a comment |
If your fragment is so simple you can use this instead
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
//ADD THIS
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//YOUR LOGIC
}
}
Other functions use for callbacks and share variable between fragments
This two is important
onCreateView : for inflate layout
onActivityCreated : for write logic codes
If your fragment is so simple you can use this instead
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false);
}
//ADD THIS
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//YOUR LOGIC
}
}
Other functions use for callbacks and share variable between fragments
This two is important
onCreateView : for inflate layout
onActivityCreated : for write logic codes
edited Jan 2 at 14:55
answered Jan 2 at 14:13
RadeshRadesh
4,35911735
4,35911735
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54007823%2fwhat-can-i-remove-to-make-an-empty-fragment-look-cleaner%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
it's like buying a car, you may never use the boot but it's still there. I am not sure if it makes the car more complicated for the user? or would it be cleaner looking without it? Auto-generated classes tend to have minimum code necessary but surely you can get rid of the parts you don't need if it is still not simple enough for you
– Ulug Toprak
Jan 2 at 14:18
You don't need to use auto-generated fragments - you can just create a new class, have it extend
Fragment
and you're done.– PPartisan
Jan 2 at 15:04