java - Android Layout Inflater 不工作?

标签 java xml android-layout layout-inflater

我的主 java 类中有一个 inflater,主要是因为我希望能够在“setContentView”(activity_main.xml) 中设置的布局之外的布局中“findViewById”。

由于我是 Android 开发人员和 Java 的新手,我认为我可以使用布局充气器来完成此操作。不管怎样,我正在尝试膨胀一个名为“box_middle”的布局。

这是我创建充气器(并尝试使用它)的代码。

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.box_middle, null);

    drawerGrid = (GridView) view.findViewById(R.id.content);

我正在像这样初始化“drawerGrid”(公共(public))

 GridView drawerGrid;

最终结果是在 XML 代码中的 GridView 所在的位置没有任何显示。

这是 XML 代码 (box_middle)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<!-- Card visible layout -->
<LinearLayout
    android:id="@+id/card_main_layout"
    style="@style/card.main_layout"
    android:orientation="vertical"
    android:layout_width="142dip"
    android:layout_height="150dip"
    android:background="#ffff0c00">

    <GridView
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>

</LinearLayout>

<!-- Compound view for Shadow
       If you want to customize this element use attr card:card_shadow_layout_resourceID -->
<it.gmariotti.cardslib.library.view.component.CardShadowView
    style="@style/card.shadow_outer_layout"
    android:id="@+id/card_shadow_layout"
    android:layout_width="150dip"
    android:layout_height="wrap_content"/>

</LinearLayout>

谢谢。

顺便说一句,我正在使用 Android Studio 和 this图书馆。

最佳答案

你用

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.box_middle, null);

膨胀 View ,但不将其附加到窗口。不要忘记使用 this.setContentView(view);

所有代码应该是:

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.box_middle, null);
this.setContentView(view);`

关于java - Android Layout Inflater 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775493/

相关文章:

java - 如何从默认包中导入类

java - 在java中获取catalina_opts

java - 如何在 Mac 上的 IntelliJ 中输入倒置的问号?

java - 如何使用 JAXB 创建没有值的 XmlElement

java - JAXB:从 Java 代码更改 XML 元素的名称?

Android 复杂表格布局

java - 在 spring 中使用条件连接点

java - 使用 JAXB 生成的 XML 中的重复字段

android - 在 ViewPager 中获取 Activity 页面并更新内容

java - 接口(interface) OnClickListener 无法使用我的 onClick 方法?