我浪费了很多时间来写这个:
private void showAbout() {
Dialog dialog = new Dialog(Generator.this);
dialog.setContentView(R.layout.about);
dialog.setTitle(getString(R.string.about));
dialog.setCancelable(true);
try {
TextView tv_version = (TextView) dialog.findViewById(R.id.tv_version);
tv_version.setText("Version number: " + getPackageManager().getPackageInfo(
getPackageName(), 0).versionName);
TextView tv_createdBy = (TextView) dialog
.findViewById(R.id.tv_createdBy);
tv_createdBy.setText(getString(R.string.made_by));
} catch (NameNotFoundException e) {
Log.e(TAG, "showAbout()", e);
} finally {
dialog.show();
}
}
希望能让我的代码更具可读性。
我写得像这样:
private void showAbout() {
About about = new About();
about.show();
}
public class About extends Activity {
String TAG = "About";
Dialog dialog;
/**
*
*/
public About() {
dialog = new Dialog(About.this);
}
public void show() {
dialog.setContentView(R.layout.about);
dialog.setTitle(getString(R.string.about));
dialog.setCancelable(true);
try {
TextView tv_version = (TextView) dialog
.findViewById(R.id.tv_version);
tv_version
.setText("Version number: "
+ getPackageManager().getPackageInfo(
getPackageName(), 0).versionName);
TextView tv_createdBy = (TextView) dialog
.findViewById(R.id.tv_createdBy);
tv_createdBy.setText(getString(R.string.made_by));
} catch (NameNotFoundException e) {
Log.e(TAG, "showAbout()", e);
} finally {
dialog.show();
}
}
}
它不起作用。它似乎在创建Dialog时崩溃了,但我不知道如何以另一种方式编写它。
有什么想法吗?
答案 0 :(得分:0)
我见过的关于扩展Activity
类的每个示例都包括覆盖onCreate
方法。因此,您应该添加onCreate
方法并通过super.onCreate(savedInstanceState);
我还认为显示的对话框不应该是一个活动。对话始终是活动的一部分。
答案 1 :(得分:0)
您可以将代码设置为创建并在基础Activity
中显示“关于”对话框,然后让其他Activites
扩展基础代码。
答案 2 :(得分:0)
鉴于您希望以pop-up
方式显示。然后你做错了。将类扩展为Activity将使其成为活动类(在活动中使用)。你应该这样做:
//class level variable
private Dialog formDialog = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
prepareDialog();
}
/**
* We prepare dialog in it's own method so that we can maintain code separation well.
* I believe there is another <em>better</em> solution. But, it work for now.
*/
private void prepareDialog() {
formDialog = new Dialog(ListDataActivity.this);
formDialog.setContentView(R.layout.form);
formDialog.setTitle("Form Buku");
// set dialog width to fill_parent
LayoutParams formDialogParams = formDialog.getWindow().getAttributes();
formDialogParams.width = LayoutParams.FILL_PARENT;
formDialog.getWindow().setAttributes(
(android.view.WindowManager.LayoutParams) formDialogParams);
txtNama = (EditText) formDialog.findViewById(R.id.txtFormNamaPenulis);
txtNama.setText( "about info" );
btnSimpan = (Button) formDialog.findViewById(R.id.btnFormSimpan);
btnBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
formDialog.hide();
}
});
}
请注意,您还需要为此对话框创建新的.xml布局。
最后,要显示它,只需要调用formDialog.show();
即可。我的android tutorial已经提取并略微修改了这个答案。