在以下示例中,我已棄用onCreateDialog
和showDialog
。我仍然可以在API中使用Android中的AlertDialog API 17嗎?
package com.dialogtest;
import android.app.Dialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CharSequence[] items = {"Google", "Apple", "Microsoft"};
// Declare the boolean array of same size as items
boolean[] itemsChecked = new boolean[items.length];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
showDialog(1);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
return new AlertDialog.Builder(this)
//.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(),
"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? " checked!" : " unchecked!"),
Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
}
我被建議使用DialogFragment,但我不太確定。
所以我想知道是不是可以直接使用AlertDialog了?
[http://stackoverflow.com/questions/10285047/showdialog-deprecated-whats-the-alternative](http://stackoverflow.com/問題/ 10285047/showdialog-deprecated-whats-the-alternative) –
已棄用並不意味着您無法使用它們。他們只是警告你現在應該避免使用這些方法,因爲它們將在未來的版本中被刪除。 –
嘗試使用Appcompat AlertDialog,我不認爲切換到appcompat版本會影響你很多:) – shadygoneinsane