programing tip

단편화 여부-활동에 대한 중첩 단편.

itbloger 2020. 11. 2. 07:42
반응형

단편화 여부-활동에 대한 중첩 단편. 두 개 이상의 활동을 사용해야하는 이유는 무엇입니까?


Activities또는 을 사용해야하는지 여부에 대한 많은 논의가 있습니다 Fragments. 예를 들면 :

내가 찾은 대부분의 토론은 Android 4.2 이전에 출시되었습니다.
Android 4.2에서 Google은 중첩 된 Fragments를 개발했습니다 .

따라서 실제로 더 이상 하나 이상의을 사용할 이유가 없습니다 Activity.

초기 단계에서는 태블릿스마트 폰 을 동시에 편안하게 Fragments지원하기 위해 앱 내에서 사용해야 했습니다.

따라서 예를 들어 항목을 클릭 ListView하면 세부 정보 View열 수있는가 있습니다 . 스마트 폰 ListView에서는 View대신 세부 정보 표시합니다 . 반면에 태블릿 은 목록을 상세보기로 대체하는 대신 두 가지 Views를 동시에 표시 할 수 있습니다 .


이제 중첩 된 Fragments다른 많은 가능성이 있습니다. 단일을 사용하려는 경우 Activity일반 정보를에 저장할 수 Activity있으며 모든 사용자 Fragment가 액세스 할 수 있습니다.

이 외에도 Fragments중첩 된 Fragments은 자녀에 대한 정보를 저장할 수도 있습니다 Fragments.

함께 Fragments내가 쉽게 재사용 할 수 있습니다 Views, 나는 더 이상 보여줄 수있는 Fragment동시에를 나는 easly 중 대화 상자를 형성 할 수있다 Fragment. 이 모든 것이 아마도 복사 및 붙여 넣기 작업에 그치지 않을 것입니다.

Activities대신 사용 하면이 작업을 수행하기 위해 많이 변경해야합니다.


저는 최근에 두 가지 사용 하여 정말 아름답고 역동적 인 것을 쉽게 얻을 있는 응용 프로그램을 구현했습니다 Fragment-ViewPager(일종 : 오늘의 정보-어제 정보). 내 생각에 Fragments우리의 삶을 더 쉽게 만들어라. :)


질문 :

  • 두 개 이상을 사용해야하는 이유는 무엇 Activity입니까?

사용하는 Activities대신 다중 사용이 더 의미 있는 좋은 예를 제공 할 수 Fragments있습니까?

  • 선택의 여지가 없지만 사용할 수있는 좋은 예가 Activities있습니까?

Maps , YouTube 및 co와 같은 더 큰 프레임 워크 대부분이 이미 지원 한다고 생각 합니다 Fragments. 따라서 우리는 Activities. 또한 그것은 아주 쉽게 처리하는 것입니다 NavigationBar, TabHosts, ViewPager, ActionBar경우에 사용 Fragments.


Udacity에서 :

항상 많은 조각이있는 하나의 활동을 생성하지 않는 이유는 무엇입니까?

  1. 복잡성 증가
  2. 더 어려운 의도 처리
  3. 읽기, 유지 관리 및 테스트가 어려움
  4. 긴밀한 결합 위험
  5. 보안 문제

먼저 하나의 활동과 중첩 된 조각 만 사용하여 거대한 애플리케이션을 작성할 수 있다는 점에 동의합니다. 이것이 소프트웨어의 재미입니다. 다양한 접근 방식을 사용하여 동일한 기능을 얻을 수 있습니다. 나에게 여러 활동을 사용하는 선택은 캡슐화, 재사용 성 및 테스트 가능성에 대한 개인적인 선호도에 달려 있습니다.

다른 애플리케이션에서 재사용 할 수있는 위젯이 있으면이를 Fragment로 만듭니다. 예를 들어, 내 앱에는 "서버와 동기화"버튼이 있으며 진행률 표시 줄을 사용하여 동기화 프로세스를 시각적으로 보여주는 사용자 지정 조각을 만들었습니다. 이 위젯을 사용할 수있는 다른 애플리케이션을 상상하기 쉽기 때문에이 위젯을 Fragment로 개발했습니다.

새 작업이 개념적으로 이전 작업과 독립적이되도록 앱 내에서 작업을 전환하는 경우 새 활동을 사용합니다. 예를 들어 내 앱의 첫 페이지에서 사용자를 선택하라는 메시지가 표시됩니다. 사용자를 클릭하면 해당 사용자의 기본 메뉴로 이동합니다. 사용자를위한이 기본 메뉴는 새 활동에 표시됩니다.

이제 크고 복잡한 앱과 해당 앱을 개발하도록 지정된 개발자 팀을 상상해 보겠습니다. 앱을 별도의 활동으로 나눌 수 있다면 작업을 나누는 것이 개념적으로 매우 쉽습니다. 각 활동은 자체 샌드 박스이므로 병렬 개발은 간단하고 단위 테스트가 가능합니다. 공통적 인 요구 사항이있는 경우에도 팀은 조각을 개발하고 재사용해야합니다. 코드 재사용은 소프트웨어 개발에서 충분히 자주 발생하지 않는다는 점을 덧붙여 야합니다.하지만 올바르게 수행된다면 재사용 가능한 조각이 많이있을 것입니다.

이제 앱을 테스트 할 때라고 가정합니다. 테스트 팀은 각 활동을 자체 블랙 박스로 취급 할 수 있습니다. 단일 활동과 수많은 중첩 조각에 의존하는 하나의 거대한 앱보다 테스트하기 쉽습니다. 버그가있는 경우 특히 중요합니다. 분명하지 않은 버그가 존재한다면 적어도 버그의 범위가 여러 활동 중 단일 활동으로 제한된다는 것을 알고 있습니다.

요약하면, 개인으로서 앱을 개발하고 있으므로 개발 결정이 다른 사람에게 영향을 미치지 않는다고 생각합니다. 더 큰 팀과 함께 앱을 개발한다면 당신의 관점은 바뀔 것입니다. 그리고 제 답변이 그 점에서 많은 의미가 있기를 바랍니다.


당신이 옳습니다. 조각만으로도 많은 일을 할 수 있습니다. 그러나 Activity 클래스 에 따르면 활동은 사용자가 수행 할 수있는 단일 집중 작업입니다. 나는 항상 내 응용 프로그램을 최상위 수준의 활동과 조각으로 구분하는 경향이 있습니다.

예를 들어 다음은 여러 활동이 의미가있는 상황입니다. 우리의 응용 프로그램에는 사용자가 로그인하면 확장 할 수있는 특정 기능이 있습니다. 그러나 사용자는 로그인하기 전에이 제한된 기능을 계속 사용할 수 있습니다. 로그인 한 경우를 제외하고 항목에 대해 댓글을 달 수 없습니다.이 경우, MainActivity는 전체 기능을 표시 할 수 있습니다. 사용자가 댓글을 달고 싶다면 요청을 저장하고 로그인 / 등록을 처리하고 작업이 완료되면 올바른 결과를 설정하는 LoginActivity 활동을 시작하여 로그인하도록 요청합니다. Fragment 또는 Activity 호출에서 결과가 LOGIN_SUCCESS인지 또는 사용자가 현재 로그인되어 있는지 확인하고 보류중인 요청을 처리합니다. 내가 말하려는 것은 로그인의 작업 흐름이 별도의 활동이어야한다는 것입니다. 그렇지 않으면 취급이 엉망이 될 것입니다. 이런 식으로, 로그인이 필요한 모든 작업은 startActivityForResult (LOGIN)를 호출하고 자신을 pendingAction으로 저장할 수 있습니다. 그런 다음 결과를 설정 한 후 super.onActivityResult에서 처리를 구현할 수 있습니다. 물론 이것은 모두 이론적이며 문제없이 조각으로 로그인을 구현할 수 있습니다. 그러나 코드는 확실히 FUed가 될 것입니다.

Another situation where you need an Activity is when your activity provides an exported Service. For example, say you are a developer of a "File Uploader" and you receive intents to upload files. It is very convenient in this case to create an Activity that can consume requests of uploading a file.

Yet, with the current updates, Fragments' functionality span most of the features of android apps and therefore can be used alone with a single host activity to fulfill the requirements of an app.

However, your whole "a single activity host" with data there is rather a weak defense. Activities and closely Fragments has the whole lifecycle that include the save/restore instance via bundles. A single host activity can be long lasting and host multiple fragments that might be recycled multiple times in a single lifetime of their activity. It is therefore highly probable that an activity holding all these instances over time to exceed its budget of resources. It is the responsibility of the developer to keep data in a shared context when they are really shared among multiple objects. This is a drawback of this approach. It does not make sense in our example for the MainActivity to consume an extra byte of data because it hosted the Login fragments when it could have slept and freed its memory if needed.

In the end, a good programmer can manage to do the same task likewise.


You are totally right!

Why should I use more than one Activity?

Could you provide any good example in which the usage of multiple Activities makes more sense instead of using Fragments?

Are there any good examples where you don't have any choice but to use Activities?

I think most of the bigger frameworks like Maps, YouTube and co already support Fragments. So we don't have to rely on Activities. Also is it quite easy to deal with NavigationBar, TabHosts, ViewPager, ActionBar in case you use Fragments.

Always using Fragments is not good for inflating the data to UI, especially in case

  • ConnectionTimeOut (or low internet) since it took much time to initialize the data. So, sometimes using each activity to inflate few data is better than each fragment.

  • Or for using method onActivityResult for more flexible, using activity is also better than. Ex. You can call FileDialogChooser in your application.

That is some cases,

Thanks,


For your questions i can only say that sometimes, with a complex User Experience or complex app that must use a different hardware component you need to use activity instead of fragment.

For example, if you have to create an app with some form that have a step that take a photo and then use this photo for some work hard memory task ( face detection for example ) that use memory you need to separate this task from the main task activity and personalise the permission on manifest to use more memory only on this activity.

Another example is if you want to use weak memory activity ( in manifest you can set properties that the clear the activity stack and force the Garbage Collector to clean memory when the activity finish )

The most probably situation that requires to use more activity and fragment is the User Experience of the app. If you need a right drawer custom that contains a menu and every fragment of the menu contains a listView and every list view must go in a detail. You can do a lot of trick to hide the right drawer and create animation to slide from fragment to the detail, but the best and simplest way is to make a new activity for the detail and manage it with a separate logic/lifecycle from the main activity with the drawer. I've done this choose in two of my apps:

iMeal - https://play.google.com/store/apps/details?id=it.fullsix.chiccopappe

GGRugby - https://play.google.com/store/apps/details?id=it.f6.template

In this app the Drawer is in the Main Fragment Activity, every menu change the content fragment. The list view in the content fragment change activity context with intent and go in another activity.

Finally there are some situation that i think you should work with more that one only fragmentActivity...but this a my pattern of work, probably you can find a trick/way or scope to do something with only an Activity and fragment.


I know I'm too late for this but Square's got opinion about fragments. Here is the gist of the article:

Fragments: lessons learned

Despite their drawbacks, fragments taught us invaluable lessons which we can now reapply when writing apps:

  • Single Activity Interface: there is no need to use one activity for each screen. We can split our app into decoupled widgets and assemble them as we please. This makes animating and lifecycle easy. We can split our widgets into view code and controller code.
  • The backstack isn’t an activity specific notion; you can implement a backstack within an activity.
  • There is no need for new APIs; everything we needed was there from the very beginning: activities, views, and layout inflaters.

You don't have to use more than one activity and you don't have to use fragments. You can just use custom views with their presenters.

You can read it here: https://corner.squareup.com/2014/10/advocating-against-android-fragments.html.

You can also find Square's mortar library here: https://github.com/square/mortar

참고URL : https://stackoverflow.com/questions/19927452/to-fragment-or-not-to-fragment-nested-fragments-against-activities-why-should

반응형