【问题标题】:Android: custom view from inflated layoutAndroid:来自膨胀布局的自定义视图
【发布时间】:2013-07-24 02:05:52
【问题描述】:

我正在基于RelativeLayout 作为代码中的类创建自己的布局

我已经掌握了 XML R.layout.menu_layout 中定义的基本布局(样式、可绘制的背景、边距、高度)

如果我不需要课程,那么我会调用 inflater 来执行此操作:

RelativeLayout menuLayout = (RelativeLayout)inflater.inflate(R.layout.menu_layout, root);

但我想改为调用我自己的班级

MenuLayout menuLayout = new MenuLayout(myparams);

由于我需要创建一个类,我需要以某种方式继承构造函数中的R.layout.menu_layout,我该怎么做?我猜视图中没有this.setLayout(res);this.setResource(res);。也许我可以在 View 构造函数中使用其他两个参数,但我也没有找到任何教程。

【问题讨论】:

  • 你能改写一下你的问题吗?
  • 新信息有帮助吗?

标签: android android-layout android-view


【解决方案1】:
public class MenuLayout extends RelativeLayout {
    public MenuLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public MenuLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public MenuLayout(Context context) {
        super(context);
        initView(context);
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.menu_layout, null);
        addView(view);
    }
}

现在你可以使用

MenuLayout menuLayout = new MenuLayout(myparams);

我认为你可以更改参数的构造函数

【讨论】:

  • 不就是把一个相对布局放到一个相对布局中吗?我也认为这是一种解决方法,但我希望有一些更清洁的方法
  • 是的,但这是我想出的。我认为这是一个干净且易于理解的解决方案。由于不必要的RelativeLayout,它可能会得到改进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多