【发布时间】:2016-01-22 16:34:14
【问题描述】:
我需要 LayoutInflater 方面的帮助。
在我的项目中,我收到“避免将null 作为视图根传递(需要解析布局参数......”lint 警告。
当在 OnCreate 方法中我有这样的事情时,这个警告来自 Activity:
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 吗?但在使用 findViewById 获取代码处理程序之前,请先使用 setContentView 设置布局
标签: android android-activity layout-inflater