如何设置扩展视图的布局(以编程方式)?

时间:2013-09-18 08:48:28

标签: android android-fragments android-view

我有Fragment创建视图。我需要它来处理多点触控事件。

片段代码:

public class ControllerFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.controller_fragment, container, false);

        TouchEventView mView = new TouchEventView(v, container);
     //...
    }

    // ...
}

但主要问题是我的观点没有布局。它只是黑色,没有按钮,textViews和 R.layout.controller_fragment

中的其他东西

那么,我应该如何将布局设置为扩展视图?

TouchEventView:

public class TouchEventView extends View {

    public TouchEventView(View v, ViewGroup container) {
       super(v.getContext());
    }

    // ...
}

1 个答案:

答案 0 :(得分:0)

我发现主要问题是TouchEventView扩展了View。它应该扩展R.layout.controller_fragment中的相同布局。

所以我将LayoutInflater添加到构造函数中并从片段中传递它。然后我从TouchEventView构造函数中扩展了布局。现在它看起来像这样:

<强>片段:

public class ControllerFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.controller_fragment, container, false);
        TouchEventView mView = new TouchEventView(v, inflater);  
    //...
    }

    // ...
}

扩展视图(布局):

public class TouchEventView extends LinearLayout {

    public TouchEventView(View v, LayoutInflater inflater) {
        super(v.getContext());
        inflater.inflate(R.layout.smart_tv_controller_fragment, this, true);
    }