一、先写一个动态布局
1、这个效果就是让控件点一变大
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
setContentView(initView());
}
private View initView() {
RelativeLayout relativeLayout = new RelativeLayout(this);
final Button bigButton = new Button(this);
// bigButton.setBackground(getDrawable(android.R.color.holo_blue_bright));
bigButton.setText("启动");
relativeLayout.addView(bigButton);
bigButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ViewGroup.LayoutParams bb = bigButton.getLayoutParams();
bb.width += 200;
bb.height += 200;
bigButton.requestLayout();
}
});
return relativeLayout;
}
}
2、在这里面貌似没有找到类似XMl布局获取ID的方法,我们在代码里添加布局,是没有生成映射的id的,所以我解决的就是,获取动态布局的全局变量,这个全局变量就是一个控件,
public class RelativePopsView extends RelativeLayout {
public ImageView ivCloce; // 图标关闭按钮
private Context context;
public ScreenPopsView screenPopsView; // 显示的图片
public RelativePopsView(Context context) {
this(context, null);
}
public RelativePopsView(Context context, AttributeSet attrs) {
this(context, null, 0);
}
public RelativePopsView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
init();
}
private void init() {
// TODO Auto-generated method stub
screenPopsView = new ScreenPopsView(context, 20);
screenPopsView.setId(Utils.generateViewId());
screenPopsView.setLayoutParams(
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
addView(screenPopsView);
ivCloce = new ImageView(context);
relativePopsView = new RelativePopsView(ctx);
screenPopsView = relativePopsView.screenPopsView;//然后可以直接操作这个我们需要的控件了
//设置最外层FrameLayout布局
final FrameLayout fl = new FrameLayout(context);
FrameLayout.LayoutParams flParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
fl.setLayoutParams(flParams);
fl.setBackgroundColor(Color.BLACK);
//设置 RelativeLayout布局
RelativeLayout rl = new RelativeLayout(context);
FrameLayout.LayoutParams rlp = new FrameLayout.LayoutParams(500, 500);
rlp.gravity = Gravity.CENTER; //这两行设置剧中显示 , 使用FrameLayout 属性中 android:layout_gravity 设置居中
rl.setBackgroundColor(Color.BLUE);
rl.setLayoutParams(rlp);
//设置图片
ImageView imageView = new ImageView(context); //设置添加的图片
RelativeLayout.LayoutParams ivParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(imageView, ivParams);
imageView.setImageResource(R.mipmap.girl);
fl.addView(rl, rlp);