在 Android 中使用片段比在视图中使用片段有什么好处?

在为 Android开发时,可以将目标(或最小) sdk 设置为4(API 1.6) ,并添加 android 兼容性包(v4)以添加对 Fragments的支持。昨天我这样做了,并成功地实现了 Fragments来可视化来自定制类的数据。

我的问题是: 与从定制对象获取视图并仍然支持 API 1.5相比,使用 Fragments有什么好处?

例如,假设我有 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

这两种方法都非常简单,创建和工作在一个活动,说,有一个 List<Foo>显示(例如,编程添加每个到一个 ScrollView) ,所以是 Fragments真的所有有用的,或者他们只是一个过度美化的简化获得一个视图,如通过上面的代码?

47816 次浏览

I'd say Fragments are useful in two scenarios: if you split up views on some devices/orientations and show them in two activities and show all the content in one on other devices. That would be a use case if you go on a tablet or maybe even in landscape mode on a phone: e.g. you show the list of items and the details on one screen. on a phone or in portrait mode you just show one part.

Another use case are reusable views. So if you have some views that are visible on different activities and also perform some actions you could put this behaviour into a fragment and then reuse it. Obviously you could probably do that with custom widgets too.

I wouldn't see any reason for using Fragments for every View and I guess it would just be an overhead. I'm only using them in the first use case and I'd say here it is a simplification.

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.

Here you can read more.

  1. Scenario Activity Split screen - We have One Layout and one activity which handle left right screen part
  2. Scenario FragmentActivity we have One layout for Main screen, one for left one for right

Scenario one is good if you have simple application.

Scenario two is good if you want to have Multiple Fragments and multiple FragmentActivities and you can combine each of those. Also you can make interaction between fragments.

I have split screen Fragmentactivity i can call it with 'Intent Extras' and tell to fragmentActivity which fragment are to be loaded. Fragments are good because they are not in manifest so you could make reusable fragments and FragmentActvity.

But it make your project larger. But if you make large project you can save many. Because you can use same Fragments or same Fragment activity.

And i thing that this fragments come little late so you must try to think in new way. Maybe just try to convert your activity to FragmentActivity. Later try to find reusable code and make Fragment from it.

Its usefull but i dont know how right now. But i have some ideas.

This is always problem. Android Team made somethink and nobody know what is good for. Because we are hardly learn like it was and here it comes some new things.

In my opinion it is good but not for reason that google tell us.

The main reason to use Fragments are for the backstack and lifecycle features. Otherwise, custom views are more light weight and simpler to implement.

At first, I actually tried to build a phone/tablet app using custom views. Everything appeared to work across phones AND tablets, even switching from single panel to split panel. Where I ran into trouble was with the back button and life cycle. Since I was simply updating views manually...there was nothing keeping track of the history of views and their states. Therefore, the back button did not work as expected and it was difficult to recreate even the latest state during life cycle events, such as when rotating the app. To fix that, I had to wrap my custom views in fragments and use the FragmentManager so that the previous states would be saved and recreated.

I realized after answering that I posted to a similar question a year earlier: https://stackoverflow.com/a/11126397/618881

Add one case when using Fragment or Activity over CustomView:

When you are using CursorLoader to observe certain views, ListView or TextView and want to update their display value whenever your ContentProvider's data updates at back end(most common case you have a service which updates your local database by polling data from remote database/cloud periodically)

One big thing all the above comments don't mention is that a fragment remains resident in memory even if Android kills the activity and restarts it when you do something like change the orientation of your device. This is done for performance reasons but can also lead to unexpected results if you were expecting fragments to be destroyed only to find that they are getting recreated out of nowhere.