小编Kai*_*i Y的帖子

Android中的片段与自定义视图

片段和自定义视图可以实现类似的功能,我知道片段比自定义视图更具可重用性,使用片段的任何其他好处/增强功能?片段是否应该取代自定义视图,或者只是针对某些特定目的的增强?

例如,下面的代码是片段:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

自定义视图的代码:

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 …
Run Code Online (Sandbox Code Playgroud)

android fragment android-custom-view

53
推荐指数
3
解决办法
3万
查看次数

标签 统计

android ×1

android-custom-view ×1

fragment ×1