怎样通过代码实现设置Activity背景为透明的,不是通过配置XML文件,是用代码实现。
-----------------------------FirstActivity.java--------------------------------
package com.self;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FirstActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 通过代码 创建布局
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER_VERTICAL);
// 添加 文本
TextView textView = new TextView(this);
textView.setText("我是背景,我是背景,我是背景,我是背景,我是背景" +
"我是测试背景");
textView.setTextColor(Color.RED);
layout.addView(textView);
// 添加按钮
Button button = new Button(this);
button.setWidth(100);
button.setHeight(60);
button.setText("打开TestActivity");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, TestActivity.class);
startActivity(intent);
}
});
layout.addView(button);
layout.setBackgroundColor(Color.BLUE);
setContentView(layout);
}
}
--------------------------------TestActivity.java-------------------------------------------
package com.self;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.nocolor);////注意该nocolor图片是透明的
this.getWindow().setBackgroundDrawable(drawable);
// 通过代码 创建布局
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setGravity(Gravity.CENTER_VERTICAL);
//添加 文本
TextView textView = new TextView(this);
textView.setText("我是上一层的文字啊,我是上一层的文字啊,我是上一层的文字啊");
textView.setTextSize(30);
textView.setTextColor(Color.GREEN);
layout.addView(textView);
setContentView(layout);
}
}
效果图: