【发布时间】:2015-09-23 00:28:30
【问题描述】:
片段和自定义视图可以实现类似的功能,我知道片段比自定义视图更可重用,使用片段还有其他好处/增强吗?片段应该替换自定义视图,还是只是出于某些特定目的的增强?
比如下面的代码是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);
}
}
自定义视图的代码:
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);
}
}
TestFragment和TestCustomView都可以创建一个由TextView和Buttons组成的视图,并使用Framelayout/fragment和com.packagename.TestCustomView的标签在activity的xml布局文件中声明,但是有什么好处呢?使用片段?
【问题讨论】:
-
我发现片段在您需要访问视图没有的东西时很有用,例如有关 Fragment 生命周期的信息,或类似“LoaderManager”的信息。
标签: android fragment android-custom-view