我发现在API21之后,我的旧对话框将丢失标题。最小的示例代码就像这样
public class MainActivity extends AppCompatActivity {
private Button btn1;
private Dialog testDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testDialog = new Dialog(MainActivity.this);
btn1 = (Button) findViewById(R.id.btnClick);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCopyDialog("some test");
}
});
}
private void showCopyDialog(final String address) {
testDialog.setTitle(address);
testDialog.setContentView(R.layout.copy_chip_dialog_layout);
testDialog.setCancelable(true);
testDialog.setCanceledOnTouchOutside(true);
Button button = (Button)testDialog.findViewById(android.R.id.button1);
String buttonTitle = "Button Title";
button.setText(buttonTitle);
testDialog.show();
}
}
copy_chip_dialog_layout
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Copy Addresses"
android:id="@android:id/button1"
android:background="@null"
android:layout_gravity="left"/>
在API21中它仍然可以显示标题,而在API24和API26中,它无法显示标题,我想知道是否必须创建DialogFragment来添加标题。
答案 0 :(得分:0)
使用 AlertDialog ,您可以在下方和21之后显示带有标题的对话框。
更改您的代码:
public class MainActivity extends AppCompatActivity {
private Button btn1;
private AlertDialog testDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btnClick);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCopyDialog("some test");
}
});
}
private void showCopyDialog(final String address) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.copy_chip_dialog_layout,null);
dialogBuilder.setCancelable(false);
dialogBuilder.setView(dialogView);
Button button = (Button)dialogBuilder.findViewById(android.R.id.button1);
button.setText("Button Title");
testDialog= dialogBuilder.create();
testDialog.show();
}
}
希望有所帮助:)