【发布时间】:2020-01-07 13:01:20
【问题描述】:
我正在尝试使用以下实现创建自定义对话框。
问题是即使我使用setContentView() 设置了布局,Android 也没有呈现布局。
.show() 被调用的例子:
我搜索了一个可能的解决方案。似乎大多数人使用AlertDialog.Builder,尽管我选择了另一种更简单且可重复使用的路线,即ProgressDialog。另外,this solution 建议将布局资源放在构造函数上——我对此表示怀疑,但自然没有用。
以下代码文件:
源文件ProgressDialog.java
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.example.android.R;
public class ProgressDialog extends Dialog {
private ProgressBar progressBar;
private TextView textView;
public ProgressDialog(@NonNull Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_dialog);
progressBar = findViewById(R.id.progressBarDialog);
progressBar.setProgress(0);
textView = findViewById(R.id.progressBarText);
}
public void setProgress(int progress){
if (progressBar != null) {
progressBar.setProgress(progress);
}
}
public void setText(String text){
if (textView != null) {
textView.setText(text);
}
}
}
并使用 progress_dialog.xml 布局如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/progressBarText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="@+id/progressBarDialog"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBarText" />
</androidx.constraintlayout.widget.ConstraintLayout>
什么原因导致这个问题,为什么Android不渲染对话框内容?
@md-asaduzzaman 的评论更新
使用方法:
ProgressDialog dialog = new ProgressDialog (SomeActivityHere.this);
dialog.show();
// optional
dialog.setProgress(0);
dialog.setText(getString(R.string.someString));
也可以传入一组参数
【问题讨论】:
-
如何使用这个对话框?
-
@Md.Asaduzzaman 查看更新
-
将您的
-
@TarunSharma 解决了这个问题。您能否将其发布为解决方案,包括有关其工作原理的详细信息,为什么它不适用于约束布局等
-
问题出在 width="0dp" 提供 android:layout_width="32dp"
标签: android dialog android-alertdialog customdialog