【问题标题】:How to add view in custom layout in runtime如何在运行时在自定义布局中添加视图
【发布时间】:2015-05-09 15:40:43
【问题描述】:

我正在创建自定义布局(扩展 FrameLayout)。我在 xml 中定义了一堆视图(现在没关系)。
我需要做什么。我的自定义布局具有自定义属性,假设它命名为 footer_banner_type
我有不同的横幅类,其中一些我彼此完全不同,所以我不能在 xml 中放置一些基本横幅。所以我必须根据属性值添加一些横幅。
我正在扩展 FrameLayout 。我是新手,这是我的第一个自定义布局。

我不知道如何提高性能。
据我了解布局迭代和膨胀所有子视图。但是如果我需要在运行时添加视图。我不想让布局重复视图层次结构,因为这将是性能问题。
我的问题是如何以更好的方式完成我的任务。

【问题讨论】:

    标签: android performance android-layout android-activity android-view


    【解决方案1】:
    //First create your view:
    View wonderfulView = new View(this.getApplicationContext());
    //Then, create its LayoutParams
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1);
    //Set those layout params in your view
    wonderfulView.setLayoutParams(params);
    //finaly, add the view to your ViewGroup
    yourLayout.addView(wonderfulView);
    

    就是这样。

    如果你想改变视图容器,你必须像这样从前一个父级中删除它:

    View movingThing = ((YourLayoutClass)findViewById(R.id.currentContainer)).getChildAt(WhereYourViewis);
    ((YourLayoutClass)findViewById(R.id.currentContainer)).removeView(movingThing);
    ((YourLayoutClass)findViewById(R.id.newContainer)).addView(movingThing);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多