如何以编程方式在片段上添加组件?

时间:2014-02-14 12:19:59

标签: android android-fragments

任何人都可以告诉我如何以编程方式在片段上添加TextFieldImageView。使用示例代码。

2 个答案:

答案 0 :(得分:3)

您应该在onCreateView

中创建TextView和ImageView
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_layout, null);

        TextView textView = new TextView(getActivity());
                ImageView imageView = new ImageView(getActivity());

                root.addView(textView);
                root.addView(imageView);

        return root;
    }

fragment_layout.xml可以包含任何布局(FrameLayout,RelativeLayout等)

答案 1 :(得分:0)

public void onViewCreated () {      
AbsoluteLayout alo = (AbsoluteLayout) this.findViewById(R.id.container);
    TextView Tv = new Textview(this.getActivity());
    Tv.setLayoutParams(new AbsoluteLayout.LayoutParams(10,10,40,40));
    Tv.setText("Added");
    alo.addView((View)Tv);
}

您可以从Fragment派生并创建一个方法,也可以这样做。