Android 에서 Dialog 사용 에 대한 자세 한 설명

21148 단어 androiddialog
Android 에 서 는 항상 Dialog 를 사용 하여 힌트 와 특수 한 효 과 를 실현 해 야 합 니 다.그리고 스타일 도 다 릅 니 다.매번 에 많은 자 료 를 찾 아야 합 니 다.반드시 해결 할 수 있 는 것 은 아 닙 니 다.여기 서 자주 사용 하 는 Dialog 의 실천 을 정리 합 니 다.
일반적인 Dialog

//   AlertDialog   
findViewById(R.id.btn_common).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 builder.setTitle("         ");
 builder.setMessage("             ");
 builder.setNegativeButton("  ", new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {
  toast("  ");
  }
 });
 builder.setPositiveButton("  ", new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {
  toast("  ");
  }
 });
 AlertDialog dialog = builder.create();
 dialog.show();
 }
});
AlertDialog 를 사용 하여 시스템 알림 대화 상 자 를 표시 합 니 다.효 과 는 다음 과 같 습 니 다.
这里写图片描述
일반 대화 상자 의 위치,크기,투명 도 를 수정 합 니 다.
주로 일반적인 dialog.show()에 다음 코드 를 추가 합 니 다.

//  show()  ,            ,  height width
Window dialogWindow = dialog.getWindow();
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); //      、  
WindowManager.LayoutParams p = dialogWindow.getAttributes(); //            
//       
p.height = (int) (d.getHeight() * 0.4); //         0.6
p.width = (int) (d.getWidth() * 0.6); //         0.65
//    
p.gravity = Gravity.BOTTOM;
//     
p.alpha = 0.5f;
dialogWindow.setAttributes(p);
여기 서 dialog 의 높이 는 화면 높이 의 4/10 이 고 너 비 는 화면 광대 역 의 6/10 이 며 동료 위 치 는 아래쪽 이 며 투명 도 는 반투명 입 니 다.물론 다른 속성 도 많 습 니 다.여 기 는 잠시 소개 하지 않 겠 습 니 다.직접 해 보 세 요.효 과 는 다음 과 같 습 니 다:
这里写图片描述
일반적인 dialog 를 사용 하여 사용자 정의 레이아웃 을 추가 합 니 다.
다음 과 같은 레이아웃 을 사용자 정의 해 야 합 니 다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="100dp"
 android:layout_height="100dp"
 android:background="#00ff00">

 <TextView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center"
 android:textColor="#ff0000"
 android:text="  "/>
</LinearLayout>

여기 서 레이아웃 설정 높이 와 너비 가 100 dp 이 고 선형 레이아웃 에 TextView 가 포함 되 어 있 습 니 다.레이아웃 이 간단 합 니 다.물론 복잡 한 레이아웃 도 사용자 정의 할 수 있 습 니 다.여 기 는 소개 하지 않 겠 습 니 다.자바 코드 의 실현 을 살 펴 보 자.

//      dialog        
findViewById(R.id.btn_custom2).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 builder.setView(R.layout.dialog_custom1);
 AlertDialog dialog = builder.create();
 dialog.show();
 }
});
우 리 는 직접 우리 의 레이아웃 을 builder 를 통 해 설정 하고 효 과 를 봅 니 다.
这里写图片描述
이 곳 의 Dialog 는 매우 추 합 니 다.이것 은 AlertDialog 의 기본 테마 와 관련 이 있 습 니 다.다음은 사용자 정의 테 마 를 통 해 대화 상자 의 스타일 을 바 꾸 어 대화 상 자 를 예 쁘 게 만 듭 니 다.
values/styles.xml 사용자 정의 스타일 에 Android:Theme.Dialog 를 계승 하여 자신의 스타일 을 구현 합 니 다.

<style name="MyCommonDialog" parent="android:Theme.Dialog">
 <!--           -->
 <item name="android:windowBackground">@android:color/transparent</item>
 <!--       -->
 <item name="android:windowIsTranslucent">false</item>
 <!--        -->
 <item name="android:windowNoTitle">true</item>
 <!--      activity   -->
 <item name="android:windowIsFloating">true</item>
 <!--        -->
 <item name="android:backgroundDimEnabled">false</item>
 <!--           -->
 <item name="android:backgroundDimAmount">0.5</item>
</style>

이 스타일 의 속성 은 모두 주석 이 있 습 니 다.스타일 이 필요 하지 않 습 니 다.자신의 가장 좋 은 효 과 를 얻 기 위해 값 을 바 꿔 보 세 요.
dialog 를 만 들 때 스타일 을 전달 합 니 다.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this,R.style.MyCommonDialog);
현재 의 효 과 는 다음 과 같다.
这里写图片描述
볼 수 있 는 우리 의 구조의 높이 와 광대 역 은 아직도 효과 가 없다.우 리 는 서브 공간의 구 조 는 보통 구조 에 의 해 측정 된다 는 것 을 알 고 있다.그래서 나 는 이 구조의 가장 바깥쪽 에 구 조 를 만들어 서 우리 의 효 과 를 얻 을 수 있 는 지 를 보고 싶다.
수정 dialogcustom 1.xml 레이아웃 은 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <LinearLayout
 android:layout_width="100dp"
 android:layout_height="100dp"
 android:layout_centerInParent="true"
 android:background="#00ff00">

 <TextView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:gravity="center"
  android:text="  "
  android:textColor="#ff0000"/>
 </LinearLayout>
</RelativeLayout>

다음 과 같이 다시 실행:
这里写图片描述
우리 가 원 하 는 효 과 를 얻 었 습 니 다.그러면 스타일 과 사용자 정의 레이아웃 을 도입 하여 다양한 대화 상자 의 효 과 를 실현 할 수 있 습 니 다.
Dialog 를 계승 하여 Dialog 를 실현 합 니 다.
Dialog 계승 을 통 해 사용자 정의 Dialog 를 실현 합 니 다.그러면 우 리 는 어디에서 든 new 우리 의 Dialog 를 직접 사용 하면 특정한 대화 상 자 를 실현 할 수 있 습 니 다.
1.values/styles.xml 에 새 스타일 MyDialog

<style name="MyDialog" parent="android:Theme.Dialog">
 <!--           -->
 <item name="android:windowBackground">@android:color/transparent</item>
 <!--       -->
 <item name="android:windowIsTranslucent">false</item>
 <!--        -->
 <item name="android:windowNoTitle">true</item>
 <!--      activity   -->
 <item name="android:windowIsFloating">true</item>
 <!--        -->
 <item name="android:backgroundDimEnabled">false</item>
 <!--           -->
 <item name="android:backgroundDimAmount">0.5</item>
</style>
2.새로운 MyDialog 계승 Dialog

public class MyDialog extends Dialog {
 //              ,               
 public MyDialog(Context context) {
 this(context, R.style.MyDialog);
 }

 public MyDialog(Context context, int themeResId) {
 super(context, themeResId);
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 //     Dialog     
 Window dialogWindow = getWindow();
 WindowManager.LayoutParams p = dialogWindow.getAttributes(); 
 p.x = 0;
 p.y = 100;
 p.gravity = Gravity.LEFT | Gravity.TOP;
 dialogWindow.setAttributes(p);
 }
}

/*
*lp.x 와 lp.y 는 원래 위치 에 대한 오프셋 을 표시 합 니 다.
*매개 변수 가 Gravity.LEFT 를 포함 할 때 대화 상자 가 왼쪽 에 나타 나 기 때문에 lp.x 는 상대 적 으로 왼쪽 의 오프셋 을 표시 하고 마이너스 값 은 무시 합 니 다.
*매개 변수 가 Gravity.Right 를 포함 할 때 대화 상자 가 오른쪽 에 나타 나 기 때문에 lp.x 는 오른쪽 에 있 는 오프셋 을 나타 내 고 마이너스 값 은 무시 합 니 다.
*매개 변수 가 Gravity.TOP 을 포함 할 때 대화 상자 가 위 에 나타 나 기 때문에 lp.y 는 상대 적 으로 위의 오프셋 을 표시 하고 마이너스 값 은 무시 합 니 다.
*매개 변수 가 Gravity.BOTTOM 을 포함 할 때 대화 상자 가 아래 에 나타 나 기 때문에 lp.y 는 상대 적 으로 아래 의 오프셋 을 표시 하고 마이너스 값 은 무시 합 니 다.
*매개 변수 에는 Gravity.CENTER 가 포함 되 어 있 습 니 다.HORIZONTAL 시 대화 상자 가 수평 으로 가운데 에 있 기 때문에 lp.x 는 수평 으로 가운데 에 있 는 위치 에서 이동 하 는 것 을 나타 낸다.
*lp.x 픽 셀,오른쪽 으로 이동 하고 마이너스 왼쪽으로 이동 합 니 다.
*매개 변수 에는 Gravity.CENTER 가 포함 되 어 있 습 니 다.VERTICAL 시 대화 상자 가 수직 으로 가운데 에 있 기 때문에 lp.y 는 수직 으로 가운데 에 있 는 위치 에서 lp.y 상 을 이동 한 다 는 뜻 입 니 다.
*소,오른쪽으로 이동 하고 음 치 는 왼쪽으로 이동 합 니 다.
*gravity 의 기본 값 은 Gravity.CENTER,즉 Gravity.CENTERHORIZONTAL | Gravity.CENTER_VERTICAL
*/
여기 서 window 의 일부 매개 변 수 를 설명 하 였 습 니 다.대화 상 자 를 왼쪽 상단 에서 100 px 까지 설정 하 였 습 니 다.
3.MyDialog 사용
사용자 정의 레이아웃 대화 상자custom2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_centerInParent="true"
 android:background="#ffffff"
 android:orientation="vertical"
 android:padding="10dp">

 <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="2dp"
  android:background="#00ff00"
  android:gravity="center"
  android:padding="10dp"
  android:text="  "
  android:textColor="#000000"/>

 <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="2dp"
  android:background="#00ff00"
  android:gravity="center"
  android:padding="10dp"
  android:text="  "
  android:textColor="#000000"/>

 <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="2dp"
  android:background="#00ff00"
  android:gravity="center"
  android:padding="10dp"
  android:text="  "
  android:textColor="#000000"/>
 </LinearLayout>
</RelativeLayout>

자바 코드

//  Dialog   Dialog
findViewById(R.id.btn_custom3).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 MyDialog dialog = new MyDialog(MainActivity.this);
 dialog.setContentView(R.layout.dialog_custom2);
 dialog.show();
 }
});

4.효과 보기:
这里写图片描述
Dialog 에 애니메이션 설정 하기
1.새 애니메이션 파일
这里写图片描述
애니메이션 dialog 에 들 어가 기enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
 android:duration="200"
 android:fillAfter="true"
 android:fromYDelta="100%p"
 android:toYDelta="0%"/>
</set>

애니메이션 대화 상자 종료exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate
 android:duration="200"
 android:fillAfter="true"
 android:fromYDelta="0%"
 android:toYDelta="100%p"/>
</set>

2.values/styles.xml 에 새 스타일 만 들 기

<style name="MyAnimDialog" parent="android:Theme.Dialog">
 <!--           -->
 <item name="android:windowBackground">@android:color/transparent</item>
 <!--       -->
 <item name="android:windowIsTranslucent">false</item>
 <!--        -->
 <item name="android:windowNoTitle">true</item>
 <!--      activity   -->
 <item name="android:windowIsFloating">true</item>
 <!--        -->
 <item name="android:backgroundDimEnabled">true</item>
 <!--           -->
 <item name="android:backgroundDimAmount">0.5</item>
 <!--    -->
 <item name="android:windowAnimationStyle">@style/dialog_animation</item>
</style>

<!--            -->
<style name="dialog_animation">
 <item name="android:windowEnterAnimation">@anim/dialog_enter</item>
 <item name="android:windowExitAnimation">@anim/dialog_exit</item>
</style>

주로 안 드 로 이 드:window Animation Style 에 우리 가 새로 만 든 애니메이션 을 지정 하면 됩 니 다.참조 가 앞 과 같 습 니 다.여기 서 보 여 줍 니 다.
3.효과 보기
这里写图片描述
Dialog 를 계승 하여 아래쪽 에 Dialog 팝 업 을 실현 합 니 다.
사용자 정의 MyBottomDialog

public class MyBottomDialog extends Dialog {
 public MyBottomDialog(Context context) {
 this(context, R.style.MyAnimDialog);
 }

 public MyBottomDialog(Context context, int themeResId) {
 super(context, themeResId);
 //                 
 View contentView = getLayoutInflater().inflate(R.layout.dialog_custom3, null);
 contentView.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  Toast.makeText(getContext(), "  ", Toast.LENGTH_SHORT).show();
  }
 });
 super.setContentView(contentView);
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 //     Dialog     
 Window dialogWindow = getWindow();
 WindowManager.LayoutParams p = dialogWindow.getAttributes();
 WindowManager m = getWindow().getWindowManager();
 Display d = m.getDefaultDisplay();
 getWindow().setAttributes(p);
 p.height = (int) (d.getHeight() * 0.6);
 p.width = d.getWidth();
 p.gravity = Gravity.LEFT | Gravity.BOTTOM;
 dialogWindow.setAttributes(p);
 }
}

onCreate 방법 에서 지정 한 Dialog 의 높이 와 너비
레이아웃 대화 상자custom3.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_centerInParent="true"
 android:background="#ffffff"
 android:orientation="vertical"
 android:padding="10dp">

 <TextView
  android:id="@+id/tv_1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="2dp"
  android:background="#00ff00"
  android:gravity="center"
  android:padding="10dp"
  android:text="  "
  android:textColor="#000000"/>

 <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="2dp"
  android:background="#00ff00"
  android:gravity="center"
  android:padding="10dp"
  android:text="  "
  android:textColor="#000000"/>

 <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="2dp"
  android:background="#00ff00"
  android:gravity="center"
  android:padding="10dp"
  android:text="  "
  android:textColor="#000000"/>
 </LinearLayout>
</RelativeLayout>

사용 하 는 방법 은 똑 같 아 요.

//  Dialog       Dialog
findViewById(R.id.btn_custom5).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 MyBottomDialog dialog = new MyBottomDialog(MainActivity.this);
 dialog.show();
 }
});

여기에 레이아웃 을 설정 할 필요 가 없습니다.왜냐하면 우 리 는 MyBottomDialog 의 구조 방법 에 레이아웃 을 미리 불 러 오고 클릭 이 벤트 를 설 치 했 기 때 문 입 니 다.
보기 효과:
这里写图片描述
사용자 정의 Meun 팝 업 Dialog
MyMenu Dialog 코드

public class MyMenuDialog extends Dialog {
 public MyMenuDialog(Context context) {
 this(context, R.style.MyDialog);
 }

 public MyMenuDialog(Context context, int themeResId) {
 super(context, themeResId);
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 //     Dialog     
 Window dialogWindow = getWindow();
 WindowManager.LayoutParams p = dialogWindow.getAttributes(); //            
 //          
 WindowManager m = getWindow().getWindowManager();
 Display d = m.getDefaultDisplay();
 DisplayMetrics outMetrics = new DisplayMetrics();
 d.getMetrics(outMetrics);
 //  WindowManager.LayoutParams
// p.height = (int) (outMetrics.heightPixels * 0.6);
// p.width = (int) (outMetrics.widthPixels * 0.4);
 //  s         x    
 p.x = (int) (15 * outMetrics.density);
 //  Title      y    
 p.y = (int) (45 * outMetrics.density);
 p.gravity = Gravity.RIGHT | Gravity.TOP;
 dialogWindow.setAttributes(p);
 }
}

사용 하면 소개 하지 않 습 니 다.여 기 는 주로 Window Manager.LayoutParams 의 x,y,gravity 를 이용 하여 이 루어 집 니 다.물론 Dialog 의 팝 업 애니메이션 을 사용자 정의 하면 메뉴 대화 상 자 를 실현 할 수 있 습 니 다.
효 과 는 다음 과 같 습 니 다:
这里写图片描述
기본적으로 Dialog 가 이러한 효 과 를 실현 하면 대부분의 프로젝트 의 수 요 를 만족 시 킬 수 있 을 것 입 니 다.다음 과 같은 복잡 한 것 은 ListView,GridView 를 가 진 Dialog 등 이 사용자 정의 Dialog 를 통 해 Dialog 를 계승 하여 이 루어 질 수 있 습 니 다.모두 조롱박 을 그 리 는 것 이면 됩 니 다.앞으로 무엇 을 만 나 서 보충 할 수 있 습 니까?

좋은 웹페이지 즐겨찾기