素材巴巴 > 程序开发 >

Android DialogFragment(2)

程序开发 2023-09-03 14:18:21


Android DialogFragment(2)

附录文章1简单介绍了如何实现一个DialogFragment,本文再介绍一种简单的方法:直接重写DialogFragment的onCreateDialog返回一个AlertDialog实现对话框。本文的例子和附录文章1不同的地方:不在依赖onCreateView。

代码运行逻辑简述:功能简单,当点击FloatingActionButton
后弹出一个自定义的DialogFragment,该DialogFragment重写了onCreateDialog,返回一个自定义的AlertDialog。

package zhangphil.app;import android.app.AlertDialog;
 import android.app.Dialog;
 import android.app.DialogFragment;
 import android.content.DialogInterface;
 import android.os.Bundle;
 import android.support.design.widget.FloatingActionButton;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.TextView;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);fab.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {MyDialogFragment dialog = new MyDialogFragment();dialog.show(getFragmentManager(), "zhangphil");}});}public static class MyDialogFragment extends DialogFragment {@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());LayoutInflater inflater = getActivity().getLayoutInflater();View view = inflater.inflate(android.R.layout.simple_list_item_1, null);TextView text = (TextView) view.findViewById(android.R.id.text1);text.setText("zhang phil @ csdn");builder.setView(view).setPositiveButton("确定",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int id) {}}).setNegativeButton("取消", null);return builder.create();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}
 }
 


代码运行结果如图:



附录文章:
1,《Android DialogFragment(1)》链接地址:http://blog.csdn.net/zhangphil/article/details/50886077



标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。