我正在嘗試爲我的片段添加動態視圖。在片段中添加動態視圖
我使用這個代碼:
@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;
}
你想要的究竟是什麼?是否有任何錯誤? – Akshay
是的,我想用myLayout替換R.layout.q1 –
有一個空的xml佈局文件,只有佈局作爲父項。使用'inflater.inflate(R ....)'來誇大你的視野。然後將您的自定義佈局附加到'rootView'。例如:'查看rootView = inflater.inflate(R.layout.q1,container,false);'然後執行'rootView.addView(myLayout);'。玩這個概念,看看是否有效。或者您可以在rootview中通過'findViewById'獲得對佈局的引用,並以這種方式追加您的自定義佈局 – john