我正在尝试为我的片段添加动态视图。
我正在使用此代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button myButton = new Button(Builtprofile.context);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout myLayout = new RelativeLayout(Builtprofile.context);
myLayout.setBackgroundColor(Color.BLUE);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
myLayout.addView(myButton, buttonParams);
View rootView = inflater.inflate(R.layout.q1, container, false);
// I want to add myLayout in place of R.layout.q1
return rootView;
}
答案 0 :(得分:2)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
Button myButton = new Button(Builtprofile.context);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
View rootView = inflater.inflate(R.layout.q1, container, false);
RelativeLayout myLayout = (RelativeLayout)rootView.findViewById(R.id.mainLayout);
myLayout.setBackgroundColor(Color.BLUE);
myLayout.addView(myButton, buttonParams);
return rootView;
}
有一个空的xml布局,只有一个名为" mainLayout"的RelativeLayout(或者你想要调用的东西)。这样你就可以附加任何动态生成的控件
答案 1 :(得分:0)
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.xml, null);
container.addView(v);