android动态布局

这篇博客主要探讨了Android中动态布局的使用,特别是相对布局和线性布局的应用。文章通过实例指出,代码和XML创建布局是相互通用的,推荐优先使用XML。在动态布局时,需注重ViewGroup中节点的关系组织,并且在设置LayoutParams的addRule时要避免越界,确保从0开始计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态布局:只涉及相对布局和线性布局


先看一个例子



import android.app.Activity;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class DynamicLayout extends Activity {
	
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout layout=new LinearLayout(this);
		
		EditText text=new EditText(this);
		EditText text1=new EditText(this);
		
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.addView(text,0);
	
		
		RelativeLayout realativeLayout=new RelativeLayout(this);
		
		    LayoutParams params=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
		    Button btn1=new Button(this);
		
		    btn1.setLayoutParams(params);
		    btn1.setId(1);
		    btn1.setText("CESHI1");
		    Button btn2=new Button(this);
		
		    RelativeLayout.LayoutParams lay2=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
//		    addRule是LayoutParams的一个方法:添加属性
		    lay2.addRule(RelativeLayout.RIGHT_OF,btn1.getId());
		    btn2.setLayoutParams(lay2);
		    btn2.setText("CESHI2");
		
		    realativeLayout.setLayoutParams(params);
		
		    realativeLayout.addView(btn1,0);
		    realativeLayout.addView(btn2,1);
		
		layout.addView(realativeLayout,1);
		layout.addView(text1,2);
		
		setContentView(layout);	
		
	};
	

}


总括起来就是三点:


1.用代码和XML的方式可以是互通的,能用XML的时候就用XML;

2.动态布局要注意组织好结点关系(ViewGroup)

3.LayoutParams的addRule要注意不要越界,一定是从0开始的


引用:[

//动态添加布局的方法1.
                LinearLayout ll = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null);
                setContentView(ll);
                  //inflater.inflate(resource, root)   第二个参数是父结点
                LinearLayout ll2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,ll);
                //这样 main2 作为 main1的子布局 加到了 main1的 根节点下
//动态添加布局的方法2 addView.       
                LinearLayout ll = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null);
                setContentView(ll);
                LinearLayout ll2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,null);
                ll.addView(ll2);

]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值