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;
}
}
}
}