Fragment i niestandardowy widok mogą osiągnąć podobną funkcję, Wiem, że fragment jest bardziej przydatny w porównaniu z niestandardowym widokiem, innymi korzyściami/ulepszeniami do używania Fragmentu? Czy fragment ma zastąpić widok niestandardowy, czy tylko ulepszenie do określonego celu?Fragment a niestandardowy widok w Androidzie
Na przykład, kod poniżej fragment:
public class TestFragment extends Fragment {
private TextView tv_name;
private Button btn_play;
private Button btn_delete;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.testfragment, container, false);
}
@Override
public void onStart() {
super.onStart();
tv_name = (TextView)getView().findViewById(R.id.tv_name);
btn_play = (Button)getView().findViewById(R.id.btn_play);
btn_delete = (Button)getView().findViewById(R.id.btn_delete);
}
}
Kod dla widoku własnego:
public class TestCustomView extends LinearLayout {
private TextView tv_name;
private Button btn_play;
private Button btn_delete;
public TestCustomView(Context context, AttributeSet attrs){
super(context, attrs);
setOrientation(LinearLayout.HORIZONTAL);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
tv_name = new TextView(context);
addView(tv_name);
btn_play = new Button(context);
addView(btn_play);
btn_delete = new Button(context);
addView(btn_delete);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.testfragment, container, false);
}
}
Zarówno TestFragment
i TestCustomView
można utworzyć widok składają TextView
i Buttons
i użyj znaczników Framelayout/fragment
i com.packagename.TestCustomView
, aby zadeklarować w działaniu " s plik układu XML, ale jakie są zalety korzystania z Fragmentu?
Fragmenty są przydatne, gdy potrzebujesz dostępu do czegoś, czego nie ma widok, np. informacje o cyklu życia Fragmentu lub coś w rodzaju "LoaderManager". – Karakuri