用编程式的方式开发UI界面

public class CodeView extends Activity 
{
    //当第一次创建该Activity时回调该方法
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //创建一个线性布局管理器
        LinearLayout layout = new LinearLayout(this);
        //设置该Activity显示layout
        super.setContentView(layout);
        layout.setOrientation(LinearLayout.VERTICAL);
        //创建一个TextView
        final TextView show = new TextView(this);
        //创建一个按钮
        Button bn = new Button(this);
        bn.setText(R.string.ok);
        bn.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT
            , ViewGroup.LayoutParams.WRAP_CONTENT));
        //向Layout容器中添加TextView
        layout.addView(show);
        //向Layout容器中添加按钮
        layout.addView(bn);
        //为按钮绑定一个事件监听器
        bn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {
                show.setText("Hello , Android , "
                    + new java.util.Date());
            }
        });
    }
}
1. bn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT , 
ViewGroup.LayoutParams.WRAP_CONTENT));
void android. view. View.setLayoutParams( LayoutParams params)

Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

一定要用父控件的LayoutParams。如果父控件是LinearLayout,当然就必须写成LinearLayout.LayoutParams,例如:

setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,TableRow.LayoutParams.FILL_PARENT));

这表示这个子控件的父布局是一个TableRow 

2.new java.util.Date():显示当地时间

转载于:https://www.cnblogs.com/crazyzx/articles/5322841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值