zoukankan      html  css  js  c++  java
  • Android开发 --代码布局

    Android开发 --代码布局

    在线性布局LinearLayout里加入view比较简单,因为属性比较少,布局简单

    示例,加入一个TextView

    LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
    TextView tv = new TextView(this);
    tv.setText("hello,world");
    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    layout.addView(tv,lp);


    在相对布局中RelativeLayout中加入view,属性较多 

    示例,加入TextView和Button,让TextView居中,并且设置Button在TextView的下方

    RelativeLayout layout;
    TextView tv = new TextView(this);
    tv.setText("hello,world");
    Button btn = new Button(this);
    btn.setText("button");
    tv.setId(0x011);
    btn.setId(0x012);
    LayoutParams tvLp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    LayoutParams btnLp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    //添加布局规则,居中于父类
    tvLp.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);
    //添加布局规则,在tv的下方
    btnLp.addRule(RelativeLayout.BELOW, tv.getId());
    layout.addView(tv,tvLp);
    layout.addView(btn,btnLp);

     public void addRule(int verb, int anchor) 方法就是给view设定布局规则,verb是规则属性,就是xml文件中的各种属性值,anchor是依靠的view的id或者比如上面的RelativeLayout.CENTER_IN_PARENT的时候就是设置true或false


    package com.example.android_activity;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.Toast;

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //动态加载布局文件
    setContentView(R.layout.activity_main);
    //使用代码动态为当前界面添加一个Button
    Button button=new Button(this);
    button.setText("代码布局");
    //设置位置
    LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    button.setLayoutParams(params);
         //给按钮设置单击事件
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    Toast.makeText(MainActivity.this,"代码布局",Toast.LENGTH_LONG).show();
    }
    });
    //获取activity_main容器,将上面的按钮加入到该容器中
    LinearLayout root=(LinearLayout) findViewById(R.id.activity_main);
    root.addView(button);
    }
    }
    如果您发现博客内容有什么错误,请您下方留言
  • 相关阅读:
    hdu 5833 Zhu and 772002 (高斯消元)
    1203事件对象
    作用域面试题
    1130 JS高级 面向对象
    1122JS中级复习
    1120浏览器对象模型 函数分析
    1119动画和复习
    1114面试题作用域
    1113Js操作CSS样式
    1112函数封装和元素的属性
  • 原文地址:https://www.cnblogs.com/zn615/p/8144308.html
Copyright © 2011-2022 走看看