利用编码实现界面

      在实际开发中可能我们会遇到一个activity的界面是不固定的,随时可能变化,这时候我们就可以利用编码来制作界面了

      在开始之前我们要介绍一个非常重要的类 ViewGroup.LayoutParams,这个类用来设置该布局或者该控件的大小(就和我们在布局文件中定义android:layout_width="fill_parent" android:layout_height="fill_parent"一样)。

具体代码如下:

     .LayoutParams layoutParams = new ViewGroup.LayoutParams(
          ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);


那么我们接下来讲讲代码编写界面的具体步骤:

(1) 创建一个控件或者布局对象:

LinearLayout linearLayout = new LinearLayout(this);

TextView textView = new TextView(this);

(2)设置控件或者布局对象的大小

LayoutParams layoutParams = new ViewGroup.LayoutParams(
           ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);


 (3)应用:布局对象和空间对象的应用是有区别的,

  布局对象的使用(应用)

   setContentView(linearLayout, layoutParams);

控件对象的应用:(因为控件是要被加载到布局对象里面去的)

TextView textView = new TextView(this);
        textView.setText(R.string.hello);
        ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.addView(textView, textViewParams);


(4)给控件或者布局添加属性

比如给布局对象添加方向:

 linearLayout.setOrientation(LinearLayout.VERTICAL);

给textview控件对象添加text

     textView.setText(R.string.hello);



完整代码如下。和上面不同的是包括不变的部分和需要改变的部分,不变的部分写在xml文件里面,变得部分写在java代码里面

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        
        TextView textView = new TextView(this);
        textView.setText(R.string.hello);
        ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.addView(textView, textViewParams);
        View partView = getPartUI();
        linearLayout.addView(partView);
        
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
        setContentView(linearLayout, layoutParams);
    }
    
    private View getPartUI(){
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return inflater.inflate(R.layout.part, null);//R.layout.part,是不变的部分
    }



 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值