Android 自定义dialog(封装好的)

喜欢把用过的东西总结一下,既可以分享,以后自己用的时候也方便查;废话不多说,先看效果:

 Android 自定义dialog(封装好的)_第1张图片

这是一个很常用的dialog ,封装一个是有必要的,用的地方太多了,实现步骤:

1:创建一个progress_dialog.xml




    

        

        
    

2:修改styles风格:

   

3:代码类:

package com.dialog.demo;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;

public class CProgressDialog
{
	private Context	mContext;
	private Dialog	mDialog;

	public CProgressDialog(Context context)
	{
		mContext = context;
	}

	public Dialog loadDialog()
	{
		mDialog = new Dialog(mContext, R.style.dialog);
		LayoutInflater in = LayoutInflater.from(mContext);
		View viewDialog = in.inflate(R.layout.progress_dialog, null);
		viewDialog.setBackgroundColor(0x7f000000);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 这里可以设置dialog的大小,当然也可以设置dialog title等
		// LayoutParams layoutParams = new LayoutParams(width * 80 / 100, 50);
		// mDialog.setContentView(viewDialog, layoutParams);
		mDialog.setContentView(viewDialog);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
		return mDialog;
	}

	public void removeDialog()
	{
		mDialog.dismiss();
	}
}

4:代最后引用地方:

package com.dialog.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;

public class MainActivity extends Activity
{
	private CProgressDialog	mDialog;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mDialog = new CProgressDialog(this);
		mDialog.loadDialog();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		mDialog.removeDialog();
		return super.onTouchEvent(event);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

这样就大功告成了

 源码下载


 

你可能感兴趣的:(Android,基础)