RelativeLayout relativeLayout = new RelativeLayout(this); relativeLayout.setId(R.id.num_layout); relativeLayout.setBackgroundColor(R.color.black); relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//实例化一个TextView控件和设置属性 TextView textView = new TextView(this); textView.setId(R.id.num_textview); textView.setTextSize(18); textView.setTextColor(getResources().getColor(R.color.white)); String txt = "1 / 1"; textView.setText(txt); textView.setGravity(Gravity.CENTER);
//给TextView添加位置布局 RelativeLayout.LayoutParams textLayout = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); textLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); textLayout.addRule(RelativeLayout.CENTER_HORIZONTAL); textLayout.setMargins(0,0,0,15);
//加入到RelativeLayout的布局里 relativeLayout.addView(textView, textLayout);
//实例化一个ImageView控件 ImageView imageView = new ImageView(this); //给ImageView控件添加布局位置信息 RelativeLayout.LayoutParams imageViewLayout = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); imageViewLayout.addRule(RelativeLayout.ABOVE, textView.getId()); imageViewLayout.addRule(RelativeLayout.CENTER_IN_PARENT); relativeLayout.addView(imageView, imageViewLayout);
最后在代码中引用布局的地方,引入relativeLayout就好了
以上代码效果图为: