Android动态布局使用 Android动态布局使用详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android动态布局使用 Android动态布局使用详解

Mr_Leixiansheng   2021-03-31 我要评论

本文为大家分享了Android动态布局的实现代码,供大家参考,具体内容如下

内容如下:介绍多种实现动态布局的方法,以及如何用代码来调整View位置

这里只介绍三种布局情况(注意不是方式)

1、无xml : 一个父类布局包含一个子父类布局,子父类布局中包含ImageView

2、无xml : 只有一个父类布局包含一个ImageView

3、有xlm布局: 通过布局ID 来进行动态布局添加

总结了下其实步骤如下:

无xml布局:

1、setContentView()之前new一个需要的布局layout,再将layout放入setContentView()

2、new 出需要的控件设置好参数(id、text···)

3、new LayoutParams 设置好控件的大小、位置属性(这里感觉和xml设置控件属性是一样的)

4、最后将params和控件放入之前new的layout即可  

有xml布局:

1、setContentView()和以前一样放入layout.xml

2、通过findViewById()找到要进行添加的布局控件

之后的步骤和无xml布局的2、3、4一样

代码如下:

1、无xml : 一个父类布局包含一个子父类布局,子父类布局中包含ImageView

RelativeLayout relativeLayout = new RelativeLayout(this);
 setContentView(relativeLayout);
 
 RelativeLayout rl = new RelativeLayout(this);
 rl.setId(11);
 ImageView imageView = new ImageView(this);
 imageView.setId(1);
 imageView.setImageResource(R.mipmap.ic_launcher);
 
 RelativeLayout.LayoutParams lpRl = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
  ViewGroup.LayoutParams.WRAP_CONTENT);
 rl.setGravity(RelativeLayout.CENTER_IN_PARENT); //设置imageView 在 rl中的位置为居中
 rl.addView(imageView, lpRl);
 
 RelativeLayout.LayoutParams lpParent = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
  ViewGroup.LayoutParams.MATCH_PARENT);
 relativeLayout.addView(rl,lpParent);

2、无xml : 只有一个父类布局包含一个ImageView

RelativeLayout relativeLayout = new RelativeLayout(this);
 setContentView(relativeLayout);
 
 ImageView imageView = new ImageView(this);
 imageView.setId(2);
 imageView.setImageResource(R.mipmap.ic_launcher);
 //params 可以理解为 imageView的位置、大小参数集合
 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
 params.addRule(RelativeLayout.CENTER_IN_PARENT);
 relativeLayout.addView(imageView,params);

3、有xlm布局: 通过布局ID 来进行动态布局添加

public class ThirdActivity extends AppCompatActivity {
 
 private LinearLayout mLinearLayout;
 
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_third);
 
 mLinearLayout = (LinearLayout) findViewById(R.id.linear_layout);
 ImageView imageView = new ImageView(this);
 imageView.setImageResource(R.mipmap.ic_launcher);
 imageView.setId(31);
 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
 params.setMargins(150, 80, 10, 0);
 mLinearLayout.addView(imageView, params);
 }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/linear_layout"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
</LinearLayout>

是不是很简单啊,了解到原理后对以后一些需要动态变化的布局操作起来就十分的方便了。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们