Lỗi fragment là gì

Đã đăng vào thg 4 19, 2019 4:31 CH 6 phút đọc

Bài đăng này đã không được cập nhật trong 3 năm

1. Giới thiệu

Fragment là một phần giao diện người dùng hoặc hành vi của một ứng dụng. Fragment có thể được đặt trong Activity hoặc một Fragment khác. Một lợi thế rất lớn của Fragment là nó đơn giản hóa việc tạo UI cho phép nhiều Fragment trên một màn hình. Fragment thì đã xuất hiện từ rất lâu các bài giới thiệu về Fragment cũng rất nhiều rồi các bạn có thể tìm hiểu vòng đời của Fragment cũng như cách triển khai với từng trường hợp.

Vì vậy tại bài viết này mình xin tập trung vào phần chính là những lỗi chúng ta thường gặp phải khi sử dụng Fragment:

  • FragmentManager: getSupportFragmentManager and getChildFragmentManager khi nào thì dùng và tránh rò rỉ bộ nhớ khi sử dụng.
  • Callback from DialogFragment, ChildFragment, BottomSheetFragment to parent fragment.
  • Khi nào thì sử dụng ViewPager, FragmentStateAdapter hay FragmentPagerAdapter.
  • Fragment receivers, broadcasts and memory leaks.
  • Fragment BottomBarNavigation and drawer. Làm thế nào để xử lý những điều này?
  • commit[] and commitAllowingStateLoss[]
  • Fragment option menus.
  • Fragment getActivity[], getView[] and NullPointers Exceptions.
  • onActivityResult with nested fragments.
  • Fragment and Bundle.
  • Back Navigation. Cũng khá khá các vấn đề rồi. Sau đây mình xin phép đi chi tiết từng cái một. Nếu thấy vẫn còn thiếu các bạn có thể bổ sung ở phần comment cho mình nhé.

2. Các vấn đề thường gặp phải

2.1 FragmentManager: getSupportFragmentManager and getChildFragmentManager

FragmentManager là Class được cung cấp bởi framework được sử dụng để tạo ra các transactions dùng để add, remove hay replace fragments.
getSupportFragmentManager: được liên kết với Activity coi nó như một FragmentManager cho Activity của bạn. Vì vậy, bất cứ khi nào bạn đang sử dụng ViewPager, bottomSheetFragment và DialogFragment trong một Activity, bạn sẽ sử dụng getSupportFragmentManager. ví dụ:

BottomDialogFragment bottomSheetDialog = bottomDialogFragment. getInstance []; bottomSheetDialog.show [getSupportFragmentManager [], "Bảng dưới cùng tùy chỉnh" ];

getChildFragmentManager được liên kết với Fragment. Bất cứ khi nào bạn là ViewPager bên trong Fragment, bạn sẽ sử dụng getChildFragmentManager. ví dụ:

FragmentManager cfManager=getChildFragmentManager[]; viewPagerAdapter = new ViewPagerAdapter[cfManager];

Để hiểu rõ hơn điều này các bạn có thể xem tại đây .
Bây giờ đến những lỗi phổ biến mà mọi người mắc phải khi họ đang sử dụng ViewPager bên trong Fragment. Khi mà không sử dụng getSupportFragmentManager với fragment manager trong activity nó sẽ gây ra các vấn đề như memory leaks, ViewPager không được update vv.... Lý do là khi chúng ta sử dụng getSupportFragmentManager các fragment sẽ được lưu vào stack của Activity tức là Parent Fragment chứa Viewpager. khi bạn kill Parent Fragment đi thì tất cả các child Fragments trong activity đó cũng sẽ không thể bị destroy vì tất cả chúng đều nằm trong bộ nhớ, nó vẫn còn tồn tại trong memory heap vì vậy sẽ gây tốn rất nhiều bộ nhớ

Đừng bao giờ thử sử dụng getSupportFragmentManager trong Fragment.

2.2 Callback from DialogFragment, ChildFragment, BottomSheetFragment to parent fragment

Đây là vấn đề rất phổ biến mà mọi người gặp phải khi họ sử dụng bottomSheetFragment hoặc DialogFragment hoặc ChildFragment. Ví dụ: Add a child fragment

FragmentTransaction ft = getChildFragmentManager[].beginTransaction[]; Fragment1Page2 fragment = new Fragment1Page2[]; ft.replace[R.id.contentLayoutFragment1Page2, fragment]; ft.setTransition[FragmentTransaction.TRANSIT_FRAGMENT_FADE]; ft.addToBackStack[null]; ft.commit[];

Một ví dụ khác bottomSheetFragment:

BottomSheetDialogFragment fragment = BottomSheetDialogFragment.newInstance[]; fragment.show[getChildFragmentManager[], fragment.getTag[]];

Hầu hết mọi người đều sử dụng interface để có thể callback lại với class parent của các fragments này. Tuy nhiên con đường tốt nhất chúng ta nên sử dụng getParentFragment[] để có thể truyền callback.

dialogFragment.show[ParentFragment.this.getChildFragmentManager[], "dialog_fragment"];

sau đó thiết lập callback cho fragment parent thêm đoạn mã sau vào đoạn con.

public void onCreate[Bundle savedInstanceState] { super.onCreate[savedInstanceState]; try { callback = [Callback] getParentFragment[]; } catch [ClassCastException e] { throw new ClassCastException["Calling fragment must implement Callback interface"]; } }

bây giờ bạn có thể gọi lại cho parent fragments của bạn một cách dễ dàng.
Sử dụng cùng một cách bạn có thể tạo callback từ fragment con trong ViewPager đến fragment parent đang chứa ViewPager .

2.3 Khi nào thì sử dụng ViewPager, FragmentStateAdapter hay FragmentPagerAdapter

FragmentPagerAdapter lưu trữ toàn bộ fragment trong bộ nhớ và có thể tăng chi phí bộ nhớ nếu sử dụng một lượng lớn các fragment trong ViewPager.
FragmentStatePagerAdapter chỉ lưu vào savedInstanceState của fragment và sẽ destroy tất cả khi mất forcus tại fragment này. Vì vậy, khi bạn sắp có nhiều Fragment, hãy sử dụng FragmentStatePagerAdapter nếu ViewPager sẽ có ít hơn ba fragment thì sử dụng FragmentPagerAdapter.

Các vấn đề thường gặp phải:

  • Update ViewPager not working:
    Điều này thưởng xảy ra do FragmentManager giữ lại instance của tất cả các fragments trong ViewPager. Một ý tưởng để làm mới lại fragment khi các config của bạn trong viewpager là đúng.
List strings = new ArrayList[]; strings.add["1"]; strings.add["2"]; strings.add["3"]; viewPager.setAdapter[new PagerFragAdapter[getSupportFragmentManager[], strings]]; strings.add["4"]; viewPager.getAdapter[].notifyDataSetChanged[];
  • Access current Fragment from ViewPager:
    Có một cách đơn giản để giải quyết vấn đề này. Chúng ta sẽ sử dụng setPrimaryItem
BlankFragment blankFragment; @Override public void setPrimaryItem[@NonNull ViewGroup container, int position, @NonNull Object object] { if [getBlankFragment[] != object] { blankFragment = [BlankFragment] object; } super.setPrimaryItem[container, position, object]; } public BlankFragment getBlankFragment[] { return blankFragment; }

Các bạn có thể xem một examples về fragment trong viewpager đơn giản tại đây

2.4 Fragment receivers, broadcasts and memory leaks.

Những sai lầm mà mọi người thường làm khi sử dụng các receivers bên trong một đoạn bị bỏ quên để hủy đăng ký receivers trong onPause hoặc OnDestroy. Nếu bạn đang đăng ký bên trong onCreate hoặc OnResume, bạn sẽ phải hủy đăng ký bên trong onPause hoặc onDestroy nếu không sẽ gây memory leak.

LocalBroadcastManager.getInstance[getActivity[]].unregisterReceiver[mYourBroadcastReceiver];

Chú ý: Bạn có một list fragments đang đăng ký receivers thì hãy đảm bảo rằng chúng được đăng ký và hủy trong onResume và onPause. Bở vì nếu theo chúng ta vẫn thường làm là đăng ký tại onCreate và hủy tại onDestroy sẽ dẫn tới các Fragment khác không thể nhận được receivers vì Fragment này không bị destroy.

3. Tổng kết

Phần 1 của bài viết này mình xin phép dừng tại đây các lỗi thường gặp của Fragment thì còn rất nhiều mình xin phép để phần 2 mình tiếp tục. Cảm ơn các bạn đã đọc bài viết.

Bye see you again


All rights reserved


Thực tế là dù cho bài viết của các bạn dùng nhiều cấu trúc câu, nhiều từ vựng khủng, từ âcđemic, idiom, idea khủng bố nhưng câu văn lại sai những lỗi ngữ pháp tối cơ bản thì liệu bạn có thể được điểm cao cho bài viết không? Bài viết ở dưới đây của mình sẽ giới thiệu một số lỗi câu cơ bản trong bài viết IELTS. Lỗi ngữ pháp không đơn thuần chỉ là lỗi về thì, mà còn nhiều vấn đề khác, đặc biệt là với văn phong Academic.

Bài viết này được mình dịch và tổng hợp từ nhiều nguồn – cả trong sách ngữ pháp lẫn nhiều tài liệu khác có trên Internet.

A Sentence Fragment – đây là một lỗi rất phổ biến, đó là việc viết câu không hoàn chỉnh. Theo định nghĩa về 1 câu trong tiếng Anh academic English, thì phải có chủ ngữ, động từ. Tuy nhiên, rất nhiều bạn chưa chắc về ngữ pháp rất cơ bản này, khi học viết IELTS đã viết thiếu các yếu tố cơ bản cấu thành nên câu kia, hoặc đôi khi đó là việc viết chỉ có một mệnh đề phụ thuộc mà không có mệnh đề độc lập. Do đó, câu không có nghĩa. Một số ví dụ dưới đây để các bạn thấy được các lỗi sai trong vấn đề này, đồng thời có cách sửa lỗi bên dưới để rút kinh nghiệm.

Incorrect:  Studying very hard on weekends. [Thiếu động từ, sự sắp xếp sai vị trí của prepositional phrase].

Correct:  Studying on weekends is very hard.

Incorrect:  Because some students work part-time while taking a full load of courses. [thiếu mệnh đề độc lập, do đó câu này không có nghĩa trong văn viết.]

Correct:  Because some students work part-time while taking a full load of courses, they have very little free-time.

Incorrect:  Tests of the Shroud of Turin have produced some curious findings. For example, the pollen of forty-eight plants native to Europe and the Middle East.

Correct:  Tests of the Shroud of Turin have produced some curious findings. For example, the cloth contains the pollen of forty-eight plants native to Europe and the Middle East.

Incorrect:  Scientists report no human deaths due to excessive caffeine consumption. Although caffeine does cause convulsions and death in certain animals.

Correct:  Scientists report no human deaths due to excessive caffeine consumption, although caffeine does cause convulsions and death in certain animals.

A run-on sentence – đây là dạng lỗi khi người viết viết nhiều hơn một mệnh đề độc lập, nhưng lại không sử dụng coordinator [liên từ] hoặc subordinator, hoặc không sử dụng hoặc sử dụng sai punctuation [câu ghép có thể được ghép giữa 2, hay nhiều mệnh đề độc lập bằng việc sử dụng dấu “;”].

Trong các ví dụ mẫu dưới đây, các bạn thấy người viết đã sửa lại lỗi của họ bằng cách sử dụng dấu “;” hoặc sử dụng coordinator hoặc subordinator [sẽ được đặt trong dấu ngoặc kép].

Incorrect:  His family went to Australia then they immigrated to Canada.

Correct:  His family went to Australia; then they immigrated to Canada

Incorrect:  Learning a new language is similar to learning to swim it takes a lot of practice.

Correct:  Learning a new language is similar to learning to swim “since” it takes a lot of practice.

Correct:  Learning a new language is similar to learning to swim; it takes a lot of practice.

Incorrect:    The experiment failed, it had been left unobserved for too long.

Correct:  The experiment failed; it had been left unobserved for too long.

Correct:  The experiment failed “because” it had been left unobserved for too long.

Incorrect:  A newly arrived international student faces many problems, for example, he has to cope with a new culture.

Correct:  A newly arrived international student faces many problems; for example, he has to cope with a new culture.

A choppy sentence – đây là lỗi mà chúng ta thường gặp khi mới bắt đầu chuyển từ nói hay viết trong general English sang academic English. Các bạn cần biết rằng, trong văn phong academic thì việc viết câu ngắn được coi là quá “nghèo nàn về phong cách” mặc dù nó hiệu quả về mặt nghĩa để miêu tả vấn đề. Cách giải quyết đó là xem lại về vấn đề cấu trúc câu, cách viết các loại câu phức, ghép, hỗn hợp và đặc biệt là phải biết cách sử dụng noun phrases để kéo dài câu hơn. Tôi sẽ phân tích rõ ràng hơn trong các ví dụ dưới đây, hi vọng các bạn sẽ rút ra được những kinh nghiệm để tránh việc này.

Incorrect:   Wind is an enduring source of power. Water is also an unlimited energy source. Dams produce hydraulic power. They have existed for a long time. Windmills are relatively new.

Correct:  Both wind and water are enduring sources of power. Dams have produced hydraulic power for a long time, but windmills are relatively new. [Ở đây, người viết đã ghép câu 1 và câu 2 bởi 2 câu này về mặt nghĩa là tương đồng nhau bằng cách sử dụng both … and …, ghép 2 câu tiếp theo bằng từ for với prepositional phrase, và đưa câu cuối vào với câu này để thành 1 câu ghép bằng cách sử dụng từ but để nối 2 mệnh đề có tính tương phản nhau.]

Incorrect:   Our results were inconsistent. The program obviously contains an error. A revision of the program is required.

Correct:  A revision of the program is required because it produced inconsistent results. [sử dụng because để nói về nguyên nhân]

A sprawl sentence – là lỗi mà người viết viết quá nhiều mệnh đề, với quá nhiều các subordinator và coordinator trong một câu, điều này trái với lỗi choopy bên trên, dẫn tới người đọc sẽ thấy khó hiểu. Tương tự, lỗi “loose sentence” thì là do người viết sử dụng quá nhiều các phrases và mệnh đề nhưng ngữ pháp và kết cấu của câu lại thiếu chặt chẽ, sắp xếp các thành phần trên không theo một trật tự nào cả, người đọc sẽ thấy rất khó hiểu với câu này. Với lỗi này, các bạn chỉ cần tách câu dài đó thành 2,3 câu ngắn hơn [tất nhiên vẫn cần tránh lỗi choopy], đồng thời sắp xếp lại các phrases và mệnh đề hợp lý. Các bạn theo dõi các ví dụ dưới đây để nhận biết và rút kinh nghiệm cho lỗi sai của mình.

Incorrect:  In the event that we get the contract, we must be ready by June 1 with the necessary personnel and equipment to get the job done, so with this end in mind a staff meeting, which all group managers are expected to attend, is scheduled for

Correct:  An all-staff meeting including all group managers is scheduled for February 12. During this meeting we should discuss the issue of personnel and equipment preparation and schedule a plan for completing the contract by June 1st, if the contract is received.

Incorrect:  The lack of rainfall has caused a severe water shortage, so people have to conserve water every day, and they also have to think of new ways to reuse water, but the situation is improving.

Correct:  The lack of rainfall has caused a severe water shortage. Although the situation is improving, people have to conserve water every day, and think of new ways to reuse water.

Incorrect:  Although the blue whale has been protected for over 30 years and its numbers are increasing, especially in the North Pacific, where whale hunting has been banned, it is still at risk of extinction as its habitat is being polluted by waste from oil tankers and its main food, the plankton, is being killed off by harmful rays from the sun, which can penetrate the earth’s atmosphere because there is a huge hole in the ozone layer over Antarctica.

Correct:  The blue whale has been protected for over 30 years, especially in the North Pacific. Although its numbers are increasing, it is still at risk of extinction. This risk is primarily caused by waste from oil tankers polluting whale habitat. Moreover, a huge hole in the ozone layer over Antarctica allows harmful rays from the sun to penetrate the earth’s atmosphere and kill the plankton, which is whale main food.

Incorrect:  The hearing was planned for Monday, December 2, but not all of the witnesses could be available, so it was rescheduled for the following Friday. [There are no grammatical errors here, but the sprawling sentence does not communicate clearly and concisely.]

Correct:  The hearing, which had been planned for Monday, December 2, was rescheduled for the following so that all witnesses would be able to attend.

Non-parallel structures – là lỗi rất phổ biến với người Việt Nam khi viết academic English. Việt viết sử dụng các cấu trúc song song là điều rất cần thiết trong khi viết academic, đặc biệt là sử dụng để so sánh, tuy nhiên, chúng ta thường lại chỉ liệt kê ra thông tin mà không hề chú ý tới một yêu cầu khi sử dụng cấu trúc song song parallel structure là 2 “vế” phải thực sự tuân theo cùng một luật về ngữ pháp và cấu trúc. Các ví dụ dưới đây sẽ giúp các bạn nhìn rõ nhất vấn đề này.

Incorrect:  The teacher wanted to know which country we came from and our future goals.

Correct:  The teacher wanted to know which country we came from and what our future goals were. [Ở câu đầu tiên, lỗi thường gặp đó là việc sử dụng được noun clause cho vế 1 mà lại không sử dụng cho vế 2. Cách sửa lỗi đơn giản nhất là sử dụng noun clause cho vế thứ 2]

Incorrect:   This report is an overview of the processes involved, the problems encountered, and how they were solved.

Correct:   This report is an overview of the processes involved, the problems encountered, and the solutions devised. [Ở câu đầu tiên, lỗi nằm ở “vế” thứ 3, đây là lỗi khi sử dụng prepositional phrase. Người viết sử dụng noun phrase trong khi ở 2 vế trước thì là noun phrase với mệnh đề quan hệ rút gọn. Cách giải quyết đó là sử dụng đúng cấu trúc như ở 2 vế trước, đồng thời tìm từ đồng nghĩa soulutions devised thay cho từ to be solved.]

Incorrect:  The candidate’s goals include winning the election, a health program, and education.

Correct:  The candidate’s goals include winning the election, enacting a national health program, and improving the educational system.

Incorrect:  Some critics are not so much opposed to capital punishment as postponing it for so long.

Correct:  Some critics are not so much opposed to sentencing convicts to capital punishment as they are to postponing executions for so long.

Nhìn chung, lỗi sai về cách viết câu trong khi viết academic đa phần đều đến từ các lỗ hổng về mặt ngữ pháp, do đó, trước khi bắt tay vào học viết IELTS, TOEFL hay academic English nói chung, các bạn cần nên bổ sung về mặt ngữ pháp trước. Trong quá trình viết nên chú ý cẩn thận về mặt ngữ pháp, nên tự có thói quen xem lại bài viết và tập luyện tự chữa bài essay cho chính bản thân mình. [nên tự chữa sau 1-2 tuần].

[Còn nữa]

Dịch và tổng hợp bởi Duc Thang Bui

Video liên quan

Chủ Đề