使用java来管理布局

来源:互联网 发布:超市广播录音软件 编辑:程序博客网 时间:2024/05/21 15:46
package com.example.ui;


import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;


public class MainActivity extends Activity {


public TextView text2;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
     FrameLayout frameLayout=new FrameLayout(this);//创建帧布局管理器
     frameLayout.setBackground(this.getResources().getDrawable(R.drawable.ic_launcher));//设置背景
     setContentView(frameLayout);
     
     TextView text1=new TextView(this);//创建TextView组件
     text1.setText("在代码中控制UI界面");//设置显示的文字
     text1.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);//设置文字大小,单位为像素
     text1.setTextColor(Color.rgb(1, 1, 1));//设置文字的颜色
     frameLayout.addView(text1);//将text1添加到布局管理器中
     
     text2 =new TextView(this);////创建TextView组件
     text2.setText("单击进入游戏......");//设置显示的文字
     text2.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);//设置文字大小,单位为像素
     text2.setTextColor(Color.rgb(1, 1, 1));//设置文字的颜色
     LayoutParams params=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
     ViewGroup.LayoutParams.WRAP_CONTENT);//创建保存布局参数的对象
     params.gravity=Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL;//设置居中显示
     text2.setLayoutParams(params);//设置布局参数
     text2.setOnClickListener(new OnClickListener(){


@Override
public void onClick(View v) {//为text2添加单击事件监听
// TODO Auto-generated method stub
//设置对话框的标题
new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage("游戏有风险,进入需谨慎,真的要进入吗?")
.setPositiveButton("确定",//为确定按钮添加单击事件
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.i("3.2", "进入游戏");//输出消息日志
}
}).setNegativeButton("退出",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.i("3.2", "退出游戏");//输出消息日志
finish();//结束游戏
}
}).show();//显示对话框
}
     
     });
     
     frameLayout.addView(text2);///将text2添加到布局管理器中
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to t
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

//这里出现了一个问题。。就是添加组件的时候是覆盖的。。这是怎么回事。。期待以后的解决啊

原创粉丝点击