我正在尝试动态创建RelativeLayout
但由于某种原因,自定义视图正在文本视图的顶部绘制。有谁知道出了什么问题以及如何将文本视图放在图纸上方?
public class MyRLayout extends android.support.v4.app.Fragment {
public MyRLayout() {}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_relativelayout, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
RelativeLayout relativelayout = v.findViewById(RelativeLayout_custom);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams paramsP1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
// add text view
TextView tv1 = new TextView(getActivity());
tv1.setText("Hello World");
TextViewCompat.setTextAppearance(tv1, android.R.style.TextAppearance_Medium);
tv1.setTextColor(Color.WHITE);
tv1.setGravity(Gravity.CENTER);
// set view for drawing1
FrameLayout frameLayoutP1 = new FrameLayout(getActivity());
paramsP1.height = fortyDp;
Drawing1 cvDrawing1 = new Drawing1(getActivity());
cvDrawing1.setLayoutParams(paramsP1);
frameLayoutP1.addView(cvDrawing1);
// generate IDs for views
tv1.setId(View.generateViewId());
frameLayoutP1.setId(View.generateViewId());
// set RelativeLayout rules for views
paramsP1.addRule(RelativeLayout.BELOW, tv1.getId());
// setLayoutParams for views
tv1.setLayoutParams(rlp1);
// add views to RelativeLayout
relativelayout.addView(tv1);
relativelayout.addView(frameLayoutP1);
super.onActivityCreated(savedInstanceState);
}
}
答案 0 :(得分:1)
tv1.setLayoutParams(rlp1);
应该是
tv1.setLayoutParams(paramsP1);
(您添加以下规则的那个)
您正在设置错误的LayoutParams。