动态添加控件

本文详细介绍了Android开发中两种常见的布局方式:线性布局(LinearLayout)与绝对布局(AbsoluteLayout)。通过XML配置和Java代码展示了如何创建线性布局,并实现动态添加按钮的功能;同时演示了绝对布局中如何精确控制组件的位置。

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

 

线性布局LinearLayout

 

xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    

</LinearLayout>


activity:

 

public class ButtonTestActivity extends Activity {
    /** Called when the activity is first created. */
	
	private LinearLayout myLayout;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myLayout = (LinearLayout)findViewById(R.id.myLayout);
        
        
        
        //动态添加7行8列按钮
        for(int j=0; j<7; j++){
        	LinearLayout childLayout = new LinearLayout(this);
            childLayout.setOrientation(LinearLayout.HORIZONTAL);//子线性布局内部为 水平排列
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,0, 1);//垂直方向上按权重来设置大小
            myLayout.addView(childLayout, params);
            
            for(int i=0;i<8; i++){
            	Button button = new Button(this);
                LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, 1);//水平方向上按权重来设置大小
                childLayout.addView(button, param);
            }
        }
        
        
        
        
    }
}


 

 

 

绝对布局AbsoluteLayout

AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(20,20, 40, 40);	
			
		
		aLayout.addView(nButton, params);//添加button在屏幕上


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值