code

뷰가 아닌 Android에서 프래그먼트를 사용하면 어떤 이점이 있습니까?

codestyles 2020. 8. 16. 20:22
반응형

뷰가 아닌 Android에서 프래그먼트를 사용하면 어떤 이점이 있습니까?


을 (를) 개발할 때 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

두 가지 방법 모두 표시 할 액티비티 List<Foo>(예 :에 각각을 프로그래밍 방식으로 추가) 가있는 액티비티에서 생성하고 작업하는 것이 매우 간단합니다 ScrollView. 따라서 Fragments정말 유용하거나 지나치게 단순화 된 것입니다. 위의 코드를 통해보기를 얻습니까?


Fragments를 사용하는 주된 이유는 백 스택 및 수명주기 기능 때문입니다. 그렇지 않으면 사용자 정의보기가 더 가볍고 구현하기가 더 간단합니다.

처음에는 실제로 사용자 지정보기를 사용하여 휴대폰 / 태블릿 앱을 구축하려고했습니다. 단일 패널에서 분할 패널로 전환하는 것까지도 모든 것이 휴대폰과 태블릿에서 작동하는 것처럼 보였습니다 . 내가 문제를 겪은 곳은 뒤로 버튼과 라이프 사이클이었습니다. 단순히 수동으로 뷰를 업데이트했기 때문에 뷰의 기록과 상태를 추적하는 것이 없었습니다. 따라서 뒤로 버튼이 예상대로 작동하지 않았고 앱을 회전 할 때와 같은 라이프 사이클 이벤트 동안 최신 상태도 재현하기 어려웠습니다. 이 문제를 해결하기 위해 사용자 지정 뷰를 조각으로 래핑하고 FragmentManager를 사용하여 이전 상태를 저장하고 다시 만들어야했습니다.

1 년 전에 비슷한 질문에 게시했다는 답변을 듣고 깨달았습니다 : https://stackoverflow.com/a/11126397/618881


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.


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.

참고URL : https://stackoverflow.com/questions/8617696/what-is-the-benefit-of-using-fragments-in-android-rather-than-views

반응형