티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Why fragments, and when to use fragments instead of activities?

프래그먼트가 필요한 이유와 액티비티 대신 프래그먼트를 사용해야 하는 경우는 언제인가요?

 문제 내용 

In Android API 11+, Google has released a new class called Fragment.

안드로이드 API 11 이상에서, 구글은 Fragment라는 새로운 클래스를 출시했습니다.

 

In the videos, Google suggests that whenever possible (link1, link2), we should use fragments instead of activities, but they didn't explain exactly why.

구글에서 제공하는 영상에서는 가능하면 액티비티 대신 프래그먼트를 사용하는 것을 권장하고 있지만, 정확한 이유에 대해서는 설명하지 않았습니다.

 

What's the purpose of fragments and some possible uses of them (other than some UI examples that can be easily be achieved by simple views/layouts)?

프래그먼트의 목적과 프래그먼트의 가능한 용도는 무엇입니까(간단한 뷰/레이아웃으로 쉽게 달성할 수 있는 일부 UI 예제 제외)?

 

My question is about fragments:

저의 질문은 프래그먼트(Fragment)에 관한 것입니다.

 

  1. What are the purposes of using a fragment?
  2. What are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
1. 프래그먼트를 사용하는 목적은 무엇인가요?
2. 액티비티/뷰/레이아웃을 사용하는 것에 비해 프래그먼트를 사용하는 장단점은 무엇인가요?

 

Bonus questions:

보너스 질문:
  1. Can you give some really interesting uses for fragments? Things that Google didn't mention in their videos?
  2. What's the best way to communicate between fragments and the activities that contain them?
  3. What are the most important things to remember when you use fragments? Any tips and warnings from your experience?
3. 가능하면 Google의 비디오에서 언급하지 않은 Fragments의 매우 흥미로운 사용 예를 제공할 수 있나요?
4. Fragment와 그들을 포함하는 액티비티 간의 가장 좋은 통신 방법은 무엇인가요?
5. Fragment를 사용할 때 기억해야 할 가장 중요한 것들은 무엇인가요? 경험에서의 팁과 경고 사항이 있나요?

 

 

 

 높은 점수를 받은 Solution 

#1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?

#1 & #2 : 프래그먼트를 사용하는 목적은 무엇이며, 액티비티/뷰/레이아웃을 사용하는 것에 비해 프래그먼트를 사용하는 장단점은 무엇인가요?

 

Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;

프래그먼트(Fragments)는 안드로이드에서 재사용 가능한 사용자 인터페이스(UI)를 만드는 해결책입니다. 레이아웃과 액티비티(Activity)를 사용하여 동일한 기능을 구현할 수 있지만(예: include를 사용하여), 프래그먼트는 안드로이드 API에서 Honeycomb 이상에서 지원되는 기능입니다. 더 자세히 설명하자면,

 

  • The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.
  • The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.
  • You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.
  • Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
  • You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.
▪ ActionBar. 액션바에 탭을 추가하여 앱을 탐색하려면 ActionBar.TabListener 인터페이스가 onTabSelected 메서드의 입력 인자로 FragmentTransaction을 제공합니다. 이를 무시하고 또 다른 방식으로 해결할 수 있지만, 이는 API와 반대로 작동하는 것입니다.

▪ FragmentManager는 매우 똑똑한 방식으로 «뒤로»를 처리합니다. 일반적인 액티비티와 달리 뒤로가기는 마지막 액티비티가 아니라 이전 프래그먼트 상태로 돌아갑니다.

▪ FragmentPagerAdapter와 함께 멋진 ViewPager를 사용하여 스와이프 인터페이스를 만들 수 있습니다. FragmentPagerAdapter 코드는 일반적인 어댑터보다 훨씬 깔끔하며, 개별 프래그먼트의 인스턴스화를 제어합니다.

▪ 폰과 태블릿 모두에 대한 애플리케이션을 만들려고 할 때 Fragment를 사용하면 생활이 훨씬 쉬워집니다. Fragment는 Honeycomb 이상의 API와 밀접하게 관련되어 있기 때문에 코드 재사용을 위해 폰에서도 사용하려고 합니다. 그것이 호환성 라이브러리가 유용한 이유입니다. 심지어 폰 전용 앱에서도 Fragment를 사용할 수 있으며 사용해야합니다.

▪이식성을 염두에 두면서. 나는 ActionBarSherlock과 호환성 라이브러리를 사용하여 버전 1.6까지 모두 동일하게 보이는 "ICS" 모양의 앱을 만듭니다. 탭, 오버플로, 분할 액션바, 뷰페이저 등 최신 기능을 모두 얻을 수 있습니다.

 

Bonus 2

보너스2

 

The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.

프래그먼트 간의 가장 좋은 통신 방법은 인텐트입니다. 프래그먼트에서 무언가를 누르면 일반적으로 해당 데이터를 포함한 StartActivity()를 호출합니다. 이 인텐트는 시작하는 액티비티의 모든 프래그먼트에 전달됩니다.

 

 

 

 가장 최근 달린 Solution 

Fragment can be thought of as non-root components in a composite tree of ui elements while activities sit at the top in the forest of composites(ui trees).

프래그먼트는 UI 요소의 복합 트리에서 루트가 아닌 구성 요소로 생각할 수 있으며, 액티비티는 복합(컴포지트) UI 트리의 상위 항목으로 위치합니다.

 

  • A rule of thumb on when not to use Fragment is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.
  • A rule of thumb on when to prefer Activity over Fragment is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.
• Fragment를 사용하지 않는 것이 바람직한 경우는, 자식 Fragment가 충돌하는 속성을 가질 때입니다. 예를 들어, 다른 스타일을 사용하거나 완전히 다른 아키텍처/논리적 차이점을 가지고 있으며 기존 트리에 균일하게 맞지 않는 경우입니다.

• Activity 대신 Fragment를 선호하는 경우는, 작업(또는 일관된 작업 세트)이 완전히 독립적이고 재사용 가능하며, 무거운 작업을 수행하고 다른 부모-자식 구성에 부담을 주지 않아야 하는 경우입니다(SRP 위배, 두 번째 책임은 구성에 맞추는 것입니다). 예를 들어, 오디오, 비디오, 사진 등을 캡처하고 편집, 잡음 제거, 사진 주석 등을 허용하는 MediaCaptureActivity와 같은 모듈입니다. 이 액티비티/모듈에는 공통 디스플레이 테마에 따르는 보다 세부적인 작업을 수행하는 자식 Fragment가 있을 수 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/10478233/why-fragments-and-when-to-use-fragments-instead-of-activities

반응형
댓글
공지사항
최근에 올라온 글