【问题标题】:How to Inflate view from XML in Android?如何在 Android 中从 XML 膨胀视图?
【发布时间】:2012-04-12 12:01:55
【问题描述】:

我正在创建一个 tableLayout [以 XML 形式给出]

添加表行[用 XML 创建并在 Java 中膨胀]

还将 2 个文本视图添加到表行 [用 XML 创建并在 JAVA 中膨胀]

我只能获取背景和文本颜色,但不能获取宽度、高度和边距等布局属性来获取表格视图。

【问题讨论】:

  • 请发布你的xml文件代码和你膨胀它的java
  • 正如您所提到的,每个表格行有 2 个文本视图,那么我建议您使用自定义适配器实现 ListView。
  • schemas.android.com/apk/res/android" android:layout_width="400dip" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="2dip" android:background="#000000" android:textColor="@color/white" />

标签: android user-interface view android-tablelayout android-inflate


【解决方案1】:
  1. 首先声明你的充气机。

    LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);
    
  2. 识别并放大您寻求在当前视图上投影的新视图。

    View view = inflater.inflate(R.layout.new_layout,null);
    
  3. 您希望将新的膨胀视图添加到您的布局中。

    main.addView(view);
    

您可以在此处参考其他信息:http://developer.android.com/reference/android/view/LayoutInflater.html

2019 年 5 月更新(Kotlin): 这就是您在 Kotlin 中从 XML 扩展视图的方式。这是指一个活动。

val view = this.layoutInflater.inflate(R.layout.dialog_upgrade, null)
mainLayout.addView(view)

【讨论】:

    【解决方案2】:
    LayoutInflater li = LayoutInflater.from(getApplicationContext());
    View cv = li.inflate(R.layout.your_layout, null);
    
    mainlayout.addView(cv);
    

    【讨论】:

      【解决方案3】:
      LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService      (Context.LAYOUT_INFLATER_SERVICE);
      View view = inflater.inflate(R.layout.your_layout,null);
      mainlayout.addView(view;
      

      按照上面的操作来放大视图。

      【讨论】:

      • 如何获取mainLayout?我们在 onCreate() 中设置 setContentView(layout)
      • mainlayout 在您的情况下将是您的 tableLayout 实例
      • 是的,我明白了你的意思并做了同样的事情。我可以在屏幕中获取视图组件 [TextView],但只应用 bg 和文本颜色,而不是我在上面的评论中给出的布局属性
      • 您可以布局参数以应用宽度、高度和边距
      • 我已经完成了,但我无法获得正确间距的 textview 组件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2023-03-26
      • 2014-03-23
      • 1970-01-01
      相关资源
      最近更新 更多