动态添加按钮片段

时间:2015-06-18 13:34:23

标签: android android-fragments

想要动态添加按钮。我试过这样:

public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){ 

    View view = inflater.inflate(R.layout.home, container, false);
    Button newText = new Button(getActivity());
    newText.setText("This is a fragment");
    newText.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT));

    return view;
}

1 个答案:

答案 0 :(得分:1)

在您的视图中,您可以添加布局,然后在布局中添加按钮, 像这样:

LinearLayout layout = (LinearLayout) view.findViewById(R.id.layoutContainer);
layout.addView(newText);