利用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

更多相关文章

  1. Android(安卓)开机Process xxx (pid xxxx) has died问题分析
  2. Android创世纪 - 第二天
  3. android fitSystemWindow属性
  4. Android万能适配器Adapter
  5. android 自定义组合控件并实现点击事件
  6. Android学习笔记(九)
  7. Android之 declare-styleable:自定义控件的属性(attr.xml,TypedAr
  8. Android:宏控属性
  9. android 怎么动态设置button 的style

随机推荐

  1. Android(安卓)4.0 wifi 和 Ethernet 的实
  2. Android(安卓)Adb指令
  3. android onGestureListener的方法
  4. [置顶] Android下的stl读取3D显示
  5. DatePickerDialog 自定义样式及使用全解
  6. Android(安卓)简单游戏实现笑脸的移动与
  7. Android模拟器快捷键大全
  8. Android(安卓)DES加密的CBC模式加密解密
  9. android中使用ant打包APK
  10. android: 如何开启webview的LBS功能