在Activity中的LayoutInflater

3
我需要帮助关于LayoutInflater。 在我的项目中,我收到了“避免将null作为视图根(需要解析布局参数…” lint警告。 这个警告来自Activity,在OnCreate方法中,我有这样的代码:
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_view, null);

这是为了举例膨胀标题。

我知道在Fragment或Adapter中使用LayoutInflater时,我有ViewGroup对象可以传递而不是null,但在Activity中遇到这种情况该怎么办?我应该抑制此警告并传递null,还是创建父对象?

编辑:

public void addTextField(String message, int textSize) {
    LinearLayout field = (LinearLayout) getLayoutInflater().inflate(R.layout.text_view_field, null);
    TextView textView = (TextView) field.findViewById(R.id.taroTextView);
    textView.setText(message);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
    textView.setSingleLine(false);
    mFieldsLayout.addView(field, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}

或者:

public class MyActionBarActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        LayoutInflater inflater = LayoutInflater.from(this);

        View customView = inflater.inflate(R.layout.action_bar_layout, null);
        actionBar.setCustomView(customView);
        actionBar.setDisplayShowCustomEnabled(true);
    }
}

}


你能不能在代码中不使用 findViewById,而是先使用 setContentView 设置布局,然后再使用 findViewById 获取代码的处理程序? - Simon
4个回答

4

为什么不直接在您的活动中调用getLayoutInflater()

如下所示:

View view = getLayoutInflater().inflate(R.layout.my_view, null);

在我的活动中,null参数不是问题。它可以正常工作。


4
您需要传递包含视图的父级元素。

例如:

ViewGroup container = (ViewGroup) findViewById(R.id.header_container);
View view = getLayoutInflater().inflate(R.layout.my_view, container, false);
container.addView(view);

这只是为了使你要填充的视图保留其与父容器相关的属性,例如边距。如果传递 null,那么这些属性将被设置为默认值。


2

这只是一个警告。有时候你需要传递 null,如果是有意为之,那么没有问题。Android 框架中的许多小部件也会这样做。

如果你想要抑制这个警告,请使用以下代码:

@SuppressLint("InflateParams")

在你的声明/方法或类上。
例如:
@SuppressLint("InflateParams")
View view = inflater.inflate(R.layout.my_view, null);

或者
 @SuppressLint("InflateParams")
void yourMethod(){
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_view, null);
}

请确保您在此处所做的操作是正确的。该警告仅用于检查代码的正确性。


您能否给我一个示例,说明在Activity中应该传递父对象而不是null的情况? - Giks91
通常用于自定义布局。您可以在此处阅读更多信息:https://possiblemobile.com/2013/05/layout-inflation-as-intended/ 您对于充气的视图要做什么? - arbrcr
这只是一个带有活动名称的标题。我有一个项目,当使用inflate添加标题或在对话框中添加文本(始终仅在片段或适配器中传递父项时)时,这是一个好方法吗? - Giks91
你能分享一些你的代码吗?我需要了解更多关于你如何使用视图对象的信息。 - arbrcr

0

这个解决方案对我有效:

View view = inflater.inflate(R.layout.my_view, (ViewGroup) getWindow().getDecorView(), false);

这样,您的View就有了一个根节点(DecorView),它不会被附加上去。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接