首页 > 系统 > Android > 正文

Android动态布局使用详解

2019-10-21 21:46:09
字体:
来源:转载
供稿:网友

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

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>

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表