Android中动态布局

package com.example.DTBJ;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

	private Context myContext;
	
	private  Button  bu_button01;
	private TextView te_text;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      //  setContentView(R.layout.activity_main);
        
        this.myContext = this;
        
        this.addView();
    }

    public void addView(){
    	
    	bu_button01 = new Button(myContext);
    	bu_button01.setText("按钮");
    	bu_button01.setId(1);
    	
    	te_text = new  TextView(myContext);
    	te_text.setText("我就是一个");
    	te_text.setId(2);
    	
    	//设置控制器
    	RelativeLayout relativeLayout = new RelativeLayout(myContext);
    	relativeLayout.setBackgroundColor(Color.WHITE);
    	
    	//给view的大小
    	LayoutParams buttonParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    	
    	LayoutParams textParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    	//添加相对布局中的布局要求
    	textParams.addRule(RelativeLayout.BELOW,bu_button01.getId());
    	//左右距离
    	textParams.setMargins(10, 10, 10, 10);
    	//设置EditText的宽度为指定大小宽度,要相应的dp转化为px
        Resources r = getResources();
        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());
        te_text.setHeight(px);
        
        //控制器添加view
        relativeLayout.addView(te_text, textParams);
        relativeLayout.addView(bu_button01, buttonParams);
        
        bu_button01.setOnClickListener(new ButtonClick());
        setContentView(relativeLayout);
    }
    
    
    private class ButtonClick implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		
		 switch (v.getId()) {
			case 1:
				
				te_text.setText("谁点击我了");
				Toast.makeText(myContext, te_text.getText().toString().trim(), Toast.LENGTH_LONG).show();
				break;

			default:
				break;
			}
		}
    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值