android在.java中手写布局

本文介绍如何使用Java代码而非XML文件实现Android应用的界面布局。文章详细解释了创建LinearLayout及TextView的过程,并展示了如何通过代码设置布局参数、背景颜色以及监听器。

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

<h1>利用java手写出布局及控件


非利用.xml进行编辑,在oncreate中如下敲出代码,其他界面同理

    //创建线性布局对象
LinearLayout layout = new LinearLayout(this);
 
//也可以这样直接定义
    // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(       
    // LinearLayout.LayoutParams.FILL_PARENT,       
    // LinearLayout.LayoutParams.WRAP_CONTENT       
    // );  
 
//设置它的属性 android:layout_width 与 android:layout_height 都为 FILL_PARENT
LinearLayout.LayoutParams layoutParams =new  LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);


//创建一个TextView,代码如下
TextView textViewleft = new TextView(this);  
 
//然后设置TextView的属性
textViewleft.setText("手写布局");

//设置id,为int型
textViewleft.setId(1);

//对于布局方面的属性这样来设置,设置width和height,
//可以为数字类型也可以为ViewGroup.LayoutParams.接上诸如fill_parent、warp_content之类的
//最后一个一代表weight属性
LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(0,ViewGroup.LayoutParams.FILL_PARENT,1);
 
//给该布局添加Margins属性,也可以单独设置如
//textviewParams.leftMargin=(50);
textviewParams.setMargins(20, 20,20,20);
 
//设置背景颜色
layout.setBackgroundColor(Color.parseColor ("#b0b0b0"));
textViewleft.setBackgroundColor(Color.parseColor ("red"));

//接着在线性布局对象中加入这个TextView
//也可以单独加入控件不加入布局
//加入的同时,也就设置了TextView相对于布局对象的布局属性textviewParms
layout.addView(textViewleft, textviewParams);

//最后一步,设置本Activity的顶级界面为线性布局
//同时也就设置了布局对象的android:layout_width 与 android:layout_height
setContentView(layout,layoutParams); 

//设置监听
textViewleft.setOnClickListener(this);
                //其他控件布局同理,关于linearlayout的横向还是纵向
                layout.setOrientation(0);// 0代表HORIZONTAL,1代表VERTICAL
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值