2014-04-01 228 views
0

我正在嘗試爲我的片段添加動態視圖。在片段中添加動態視圖

我使用這個代碼:

@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

你想要的究竟是什麼?是否有任何錯誤? – Akshay

+0

是的,我想用myLayout替換R.layout.q1 –

+1

有一個空的xml佈局文件,只有佈局作爲父項。使用'inflater.inflate(R ....)'來誇大你的視野。然後將您的自定義佈局附加到'rootView'。例如:'查看rootView = inflater.inflate(R.layout.q1,container,false);'然後執行'rootView.addView(myLayout);'。玩這個概念,看看是否有效。或者您可以在rootview中通過'findViewById'獲得對佈局的引用,並以這種方式追加您的自定義佈局 – john

回答

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; 
} 

曾經使用過被稱爲 「mainLayout」(或者你想叫它什麼都)一RelativeLayout的一個空的XML佈局。這樣你可以附加任何動態生成的控件

+0

非常感謝您,它的工作原理 –

+1

歡迎您的朋友 – john

0
LayoutInflater vi = (LayoutInflater) getActivity() 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View v = vi.inflate(R.layout.xml, null); 

container.addView(v);