【问题标题】:How to inflate xml-layout into child View如何将 xml-layout 膨胀到子视图中
【发布时间】:2013-08-16 09:42:07
【问题描述】:

我正在尝试将 xml-layout 扩展为自定义 View-class,然后将其放入实际软件中的 LinearLayout 中。经过一番谷歌搜索后,我设法创建了自定义类,该类通过使用以下类来扩展布局:

    public class LitteringView extends RelativeLayout
{

    public LitteringView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        View.inflate(context, R.layout.littering_layout, this);

    }


    public LitteringView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // TODO Auto-generated method stub
         for(int i = 0 ; i < getChildCount() ; i++){
             getChildAt(i).layout(l, t, r, b);
         }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }





}

现在当我将它添加到线性布局时它肯定会膨胀:

layout.addView(new LitteringView(getActivity()));

问题是它占据了整个屏幕,而屏幕应该在 LinearLayout 的三个孩子之间平均分配。其他视图也是动态创建的。我怎样才能防止它占用整个空间?

我正在尝试创建一个自定义视图/类并将其功能打包在其中,然后我可以轻松地将其添加到父布局(在本例中为 LinearLayout),同时希望利用 xml 来定义视图的布局。

【问题讨论】:

    标签: android view android-relativelayout layout-inflater


    【解决方案1】:

    您需要为视图使用“权重”。一个简单的例子:

    Layout.LayoutParams params = new LinearLayout.LayoutParams(width, height, weight);
    

    您需要针对您的情况对其进行优化。为您的所有视图平等地赋予权重值(例如:所有视图为 1),它们应该共享视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多