Android的DialogFragment的基本使用
1.API不小于11;
2.使用方法:
(1)新建对话框的类必须继承于DialogFragment:
对话框中有一按钮,点击按钮后关闭对话框。
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 @SuppressLint("ValidFragment") 2 public class MatchDialog extends DialogFragment { 3 4 public MatchDialog() { 5 } 6 7 Dialog mDialog; 8 MatchTextView matchTextView; 9 MatchButton mMatchButton; 10 11 @Override 12 public Dialog onCreateDialog(Bundle savedInstanceState) { 13 if (mDialog == null) { 14 mDialog = new Dialog(getActivity(), R.style.cart_dialog); 15 mDialog.setContentView(R.layout.dialog_match); 16 mDialog.setCanceledOnTouchOutside(true); 17 mDialog.getWindow().setGravity(Gravity.CENTER); 18 View view = mDialog.getWindow().getDecorView(); 19 matchTextView = (MatchTextView) view.findViewById(R.id.mTextView); 20 matchTextView.setMatchOutListener(new MatchView.MatchOutListener() { 21 @Override 22 public void onBegin() { 23 24 } 25 26 @Override 27 public void onProgressUpdate(float progress) { 28 } 29 30 @Override 31 public void onFinish() { 32 MatchDialog.super.onStop(); 33 } 34 }); 35 36 mMatchButton = (MatchButton) view.findViewById(R.id.mButton); 37 mMatchButton.setOnClickListener(new View.OnClickListener() { 38 @Override 39 public void onClick(View v) { 40 mMatchButton.hide(); 41 matchTextView.hide(); 42 } 43 }); 44 } 45 return mDialog; 46 } 47 }
(2)调用对话框的Activity要继承FragmentActivity:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class MainActivity extends FragmentActivity { 2 3 private MatchTextView mMatchTextView; 4 private SeekBar mSeekBar; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 11 mMatchTextView = (MatchTextView) findViewById(R.id.mMatchTextView); 12 mSeekBar = (SeekBar) findViewById(R.id.mSeekBar); 13 mSeekBar.setProgress(100); 14 mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 15 @Override 16 public void onProgressChanged(SeekBar seekBar, int progress, 17 boolean fromUser) { 18 mMatchTextView.setProgress(progress * 1f / 100); 19 } 20 21 @Override 22 public void onStartTrackingTouch(SeekBar seekBar) { 23 24 } 25 26 @Override 27 public void onStopTrackingTouch(SeekBar seekBar) { 28 29 } 30 }); 31 32 findViewById(R.id.mButton).setOnClickListener( 33 new View.OnClickListener() { 34 @Override 35 public void onClick(View v) { 36 showMatchDialog(); 37 } 38 }); 39 } 40 41 protected void showMatchDialog() { 42 MatchDialog matchDialog = new MatchDialog(); 43 getSupportFragmentManager().beginTransaction().add(matchDialog, "matchDialog").commit(); 44 } 45 46 }