문제

I am trying to add a dynamic view for my fragment.

I am using this code:

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

}
도움이 되었습니까?

해결책

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

Have an empty xml layout with just a RelativeLayout called "mainLayout"(or what ever you want to call it). That way you can append any dynamically generated controls

다른 팁

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

container.addView(v);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top