【问题标题】:Inflating a custom layout view into a Layout extending class in Android将自定义布局视图膨胀为 Android 中的 Layout 扩展类
【发布时间】:2013-01-15 16:14:05
【问题描述】:

我在 XML 文件中定义了一个自定义布局,它有一个带有一堆子视图的 RelativeLayout 根。

现在,我定义了以下类:

public class MyCustomView extends RelativeLayout {

    public MyCustomView(Context context) {
        super(context);
        init();
    }

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();     
    }

    public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);    
        init();
    }

    private void init() {
        LayoutInflater inflater = (LayoutInflater)  getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.my_custom_view, this, true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        Log.d("Widget", "Width spec: " + MeasureSpec.toString(widthMeasureSpec));
        Log.d("Widget", "Height spec: " + MeasureSpec.toString(heightMeasureSpec));

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int chosenWidth = chooseDimension(widthMode, widthSize);
        int chosenHeight = chooseDimension(heightMode, heightSize);

        int chosenDimension = Math.min(chosenWidth, chosenHeight);

        setMeasuredDimension(chosenDimension, chosenDimension);
    }

    private int chooseDimension(int mode, int size) {
        if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
            return size;
        } else { 
            return getPreferredSize();
        }
    }

    private int getPreferredSize() {
        return 400;
    }
}

如您所见,我将 root 设置为 MyCustomView 实例并将附加标志设置为 true。

我想要实现的是,当我将这个自定义视图添加到另一个布局的 xml 中时,它将实例化 MyCustomView 类,该类将在 XML 中定义布局。

我已经尝试使用<merge> 标记,但是这样我就无法按照我的意愿在 XML 中排列我的子视图。

我还尝试扩充 XML 并将其作为视图添加到 MyCustomView,但这样我就得到了多余的 RelativeLayout

最后,我添加了onMeasure() 只是为了完整。

【问题讨论】:

  • 你的问题是来自R.layout.widget_view的视图没有出现在Widget组件中,对吧?
  • 没错。发生膨胀,但未显示子视图。

标签: android android-custom-view layout-inflater


【解决方案1】:

膨胀发生但子视图没有显示

RelativeLayout 比您在 onMeasure 布局中所做的更多(很多)(基本上,孩子们根本没有用您的代码衡量,所以他们没有要展示的东西) .如果您扩展 ViewGroup 之类的 RelativeLayout,则需要让该类执行其回调(onMeasureonLayout),或者至少,非常小心地复制方法并根据需要进行修改(如果您想看看什么)。

因此,删除 onMeasure 方法以查看子项或更好地解释为什么要覆盖它。

【讨论】:

  • @Daniel 确保将其完全删除,如果您发布 my_custom_view 布局文件也不会受到影响。
  • 谢谢,你是对的!顺便说一句,我添加了 onMeasure() 以强制我的视图宽度和高度相等。知道如何以不同的方式做到这一点吗?
猜你喜欢
  • 2013-07-24
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
相关资源
最近更新 更多