【发布时间】:2012-01-26 21:50:57
【问题描述】:
在为Android 开发时,您可以将目标(或最小)sdk 设置为 4 (API 1.6) 并添加 android 兼容包 (v4) 以添加对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
这两种方法的创建和使用都很简单有用,或者它们只是通过上面的代码获得视图的过度美化简化?
【问题讨论】:
-
片段不一定要有 UI,它们可以是可重用的行为。在这种情况下,视图将是多余的。
-
我已经在另一个问题中回答了这个问题。请参阅stackoverflow.com/a/14912608/909956T;dr - 有时片段允许您创建比依赖自定义视图实现更多的可重用组件。查看链接了解原因。
标签: android android-fragments android-view android-lifecycle software-design