When developing for Android
, you can set your target (or minimum) sdk to 4 (API 1.6) and add the android compatibility package (v4) to add support for Fragments
. Yesterday I did this and successfully implemented Fragments
to visualize data from a custom class.
My question is this: what is the benefit for using Fragments
as opposed to simply getting a View from a custom object, and still supporting API 1.5?
For example, say I have the class Foo.java:
public class Foo extends Fragment {
/** Title of the Foo object*/
private String title;
/** A description of Foo */
private String message;
/** Create a new Foo
* @param title
* @param message */
public Foo(String title, String message) {
this.title = title;
this.message = message;
}//Foo
/** Retrieves the View to display (supports API 1.5. To use,
* remove 'extends Fragment' from the class statement, along with
* the method {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)})
* @param context Used for retrieving the inflater */
public View getView(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.foo, null);
TextView t = (TextView) v.findViewById(R.id.title);
t.setText(this.title);
TextView m = (TextView) v.findViewById(R.id.message);
m.setText(this.message);
return v;
}//getView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.foo, null);
TextView t = (TextView) v.findViewById(R.id.title);
t.setText(this.title);
TextView m = (TextView) v.findViewById(R.id.message);
m.setText(this.message);
return v;
}//onCreateView
}//Foo
Both methods are very simple to create and to work with in an Activity that, say, has a List<Foo>
to display (for example, programmatically adding each to a ScrollView
), so are Fragments
really all that useful, or are they just an over-glorified simplification of getting a View, such as through the code above?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…