自定义View-1-动态添加view
效果图
//在代码中实现添加布局
- 1
- 1
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:id="@+id/ll_add_context"
android:background="#424242"
android:layout_height="match_parent">
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#566667"
android:gravity="center"
android:text="FIRST"/>
</LinearLayout>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
主页面代码
public class AFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_a,null);
LinearLayout linearLayout=(LinearLayout)view.findViewById(R.id.ll_add_context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView=new TextView(getActivity());
textView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
textView.setText("I am new text");
linearLayout.addView(textView);//添加view
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(200,200);
linearLayout.getChildAt(1).setLayoutParams(params);//父控件给子view设置布局参数
TextView button=new TextView(getActivity());
button.setText("I am the button");
button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
linearLayout.addView(button);//添加view
RelativeLayout relativeLayout=new RelativeLayout(getActivity());
LinearLayout.LayoutParams params2=new LinearLayout.LayoutParams(400,400);
relativeLayout.setLayoutParams(params2);
relativeLayout.setBackgroundColor(getResources().getColor(R.color.green));
RelativeLayout.LayoutParams params3=new RelativeLayout.LayoutParams(150,250);
TextView textView2=new TextView(getActivity());
textView2.setId(Integer.valueOf(1));//设置viewID
textView2.setLayoutParams(params3);//view直接设置布局参数
textView2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
textView2.setText("I am new text 2");
relativeLayout.addView(textView2);
RelativeLayout.LayoutParams params4=new RelativeLayout.LayoutParams(150,150);
params4.addRule(RelativeLayout.BELOW,textView2.getId());//父控件为RelativeLayout时,设置布局属性的规则
TextView button2=new TextView(getActivity());
button2.setText("I am the button 2");
button2.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
relativeLayout.addView(button2);
relativeLayout.getChildAt(1).setLayoutParams(params4);
linearLayout.addView(relativeLayout);
return view;
}
}

浙公网安备 33010602011771号