首先,这是片段的代码:
public class MyFragment extends Fragment {
private View FragmentView;
public static Fragment newInstance() {
MyFragment NewFragment = new MyFragment();
return NewFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentView = inflater.inflate(
R.layout.tasks,
new LinearLayout(MainActivity.MainContext)
);
FragmentView.setLayoutParams(
new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT
)
);
addText();
return FragmentView;
}
private void addText() {
TasksView.setBackgroundResource(R.drawable.bg_image);
TextView MyTitle = new TextView(MainActivity.MainContext);
MyTitle.setLayoutParams(
new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
)
);
MyTitle.setText(R.string.mytitle);
((LinearLayout) FragmentView).addView(MyTitle );
}
}
MainActivity.MainContext
在主要活动的课程中存储为public static
,并在getApplicationContext()
创建活动时检索。
现在,问题出现在这里:
FragmentView = inflater.inflate(
R.layout.tasks,
new LinearLayout(MainActivity.MainContext)
);
因此,片段内不会显示MyTitle
文本视图。如果我这样做:
FragmentView = inflater.inflate(R.layout.tasks, null);
显示但我收到警告:
Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element)
我想要正确地做,没有得到任何警告,我找不到办法。我也尝试过:
FragmentView = inflater.inflate(R.layout.tasks, container);
但是应用程序崩溃了。
答案 0 :(得分:6)
您应该将container
作为父母传递。
FragmentView = inflater.inflate(
R.layout.tasks,
container,
false
);
此外,您应指定false
,因此LayoutInflater
不会将夸大的视图附加到父级。膨胀的视图通过FragmentManager
附加到父级。