【问题标题】:Adding view programmatically doesn't work以编程方式添加视图不起作用
【发布时间】:2015-04-01 06:14:42
【问题描述】:

我有一个以编程方式扩展的父自定义布局(LinearLayout 的子布局)。

在构造函数中,我添加另一个布局作为父布局的子布局,如下所示:

public ExtendedContentLinearLayout(Context context) {
    super(context);
    this.context = context;

    this.setClickable(false);

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mTrigger = inflater.inflate(R.layout.nav_menu_board_expandable_children_outer, this, true);
    mTrigger.setOnClickListener(this);
    mTrigger.setBackgroundResource(R.color.da_blue);


}

父布局和“触发器”布局(上面刚刚添加的子布局)工作正常并显示良好。

一旦用户触摸了这个“触发”布局,我想向父级添加一个新的子级 - 另一个包含更多内容的布局,因此我需要父级布局来扩展并包含新添加的布局,但这不起作用!

单击触发器布局不会添加新布局(至少没有显示在屏幕上)。这是点击调用(点击事件正在工作):

   @Override
    public void onClick(View v) {
        App.disableTouchEventForDefaultDuration();

    Log.d("CLICKED", "CLICKED");


    LinearLayout mContent = new LinearLayout(context);
    mContent.setOrientation(HORIZONTAL);
    mContent.setBackgroundResource(R.color.da_indicator_pink);
    mContent.setVisibility(VISIBLE);
    ExtendedContentLinearLayout.this.addView(mContent);


}

【问题讨论】:

  • 当你点击现在到底发生了什么?它是否显示任何错误?
  • 完全没有错误。只是视图没有显示。
  • 父布局是设置为固定大小还是设置为包裹内容?

标签: android android-linearlayout android-viewgroup


【解决方案1】:

我最终在 XML 中创建了布局,然后使用:

 View view = inflater.inflate(this.layout, null, false);

然后使用添加此视图 添加视图(视图)

这对我来说很好用

【讨论】:

    【解决方案2】:
    mContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    

    请试试上面的代码,试试 WRAP_CONTENT 和 MATCH_PARENT

    【讨论】:

      【解决方案3】:

      就我而言,layout.post 有效

      ExtendedContentLinearLayout.this.post( new Runnable() {
          @Override
          public void run() {
              ExtendedContentLinearLayout.this.addView(llhItem);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2014-08-24
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多