透明对话框
程序员文章站
2022-05-29 09:54:26
...
最近需要实现一个透明对话框效果,上网查了很多关于对话框背景透明的资料,做出来的效果如下图,点击Button1弹出对话框,虽然设置对话框的背景为透明,但是实际显示黑色。
而我想实现的是如下效果,于是只能自己修改
实现代码如下:
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class LoadingActivity extends Activity {
private Button button1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(LoadingActivity.this, R.style.dialog);
dialog.setContentView(R.layout.loading_dialog);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
}
});
}
}
注意一定要有: dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);否则黑色背景无法去掉。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ProgressBar android:id="@+id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" style="?android:attr/progressBarStyleSmall" android:layout_centerVertical="true" /> <TextView android:layout_toRightOf="@id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="正在获取数据" android:layout_centerVertical="true" android:gravity="center" /> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="dialog" parent="@android:style/Theme.Dialog"> <item name="android:windowFrame">@null</item> <item name="android:windowIsFloating">true</item> <item name="android:windowIsTranslucent">true</item> <item name="android:windowNoTitle">true</item> <item name="android:background">@null</item> <item name="android:windowBackground">@null</item> <item name="android:backgroundDimEnabled">false</item> </style> </resources>
另外,在AndroidManifest.xml的Activity声明中要添加android:configChanges="orientation",否则旋转屏幕时会出现WindowLeaked错误,导致对话框消失。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.lanhuidong.loaddialog" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="4" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="LoadingActivity" android:configChanges="orientation" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
上一篇: 手把手教你CIFAR数据集可视化