在Android
为Fragments
. 昨天我这样做并成功实现Fragments
了自定义类的数据可视化。
我的问题是:Fragments
与简单地从自定义对象获取视图相比,使用它有什么好处,并且仍然支持 API 1.5?
例如,假设我有类 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
这两种方法在一个 Activity 中创建和使用都非常简单,比如说,有一个List<Foo>
要显示的(例如,以编程方式将每个添加到 a ScrollView
),所以它们Fragments
真的很有用,或者它们只是过度美化的简化得到一个视图,比如通过上面的代码?