티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to create a Custom Dialog box in android?

안드로이드에서 커스텀 다이얼로그 상자는 어떻게 만드나요?

 문제 내용 

I want to create a custom dialog box like below

저는 아래와 같은 커스텀 다이얼로그 박스를 만들고 싶습니다.

 

enter image description here

I have tried the following things.

제가 시도해 본 것은 다음과 같습니다.

 

  1. I created a subclass of AlertDialog.Builder and used a custom Title and Custom Content View and used that but the result was not as expected.
  2. Another attempt was to subclass DialogFragment and customize the dialog inside onCreateDialog that but result was not as expected.
  3. Then I tried using a plain Dialog class. The result was not as expected.
1. AlertDialog의 하위 클래스를 만들었습니다.사용자 지정 제목 및 사용자 지정 내용 보기를 작성하고 사용했으며 이를 사용했지만 결과가 예상보다 좋지 않았습니다.
2. 또 다른 시도는 DialogFragment를 하위 분류하고 CreateDialog에서 내부 대화 상자를 사용자 지정하는 것이었지만 결과가 예상과 같지 않았습니다.
3. 그런 다음 일반 대화 상자 클래스를 사용해 보았습니다. 결과가 예상과 달랐다.

 

In all three cases, the problem is when I overlook the title view the size of the dialog is not as expected and when I use Title view the result is there is a thick border around the content view (which really looks bad). Now I have two questions in my mind...

세 가지 모두에서 문제는 제목 뷰를 놓치면 대화 상자의 크기가 예상과 다르며, 제목 뷰를 사용하면 콘텐츠 뷰 주위에 두꺼운 테두리가 있는 것으로 나타났습니다 (실제로 보기가 좋지 않습니다). 이제 제 마음에 두 개의 질문이 있습니다...

 

  1. How can I achieve that? As I have already tried so many things, a direct answer will be more appreciated.
  2. What is the best way to show an error or alert dialog in an android app?
1. 어떻게 이를 달성할 수 있을까요? 이미 많은 것들을 시도해봤기 때문에, 직접적인 답변이 더욱 감사할 것입니다.
2. 안드로이드 앱에서 오류 또는 경고 대화상자를 보여주는 가장 좋은 방법은 무엇일까요?

 

EDIT Android Developer Documentation recommends that we should use either DialogFragments or Dialogs for showing Error / Alert Messages to the user. However at one point they say ...

편집 : 안드로이드 개발자 문서는 오류 / 경고 메시지를 사용자에게 표시하는 데 DialogFragment 또는 Dialog를 사용하는 것이 좋다고 권장합니다. 그러나 어느 한 지점에서 다음과 같이 언급합니다...

 

Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the manifest element.

팁: 사용자 정의 대화 상자를 원하는 경우 Dialog API 대신 Activity를 대화 상자로 표시할 수 있습니다. Activity를 만들고 manifest 요소에서 Theme.Holo.Dialog로 테마를 설정하면 됩니다.

 

What is the meaning of that? Isn't it too much to use an Activity just for showing an error message???

그 의미는 무엇인가요? 단순히 오류 메시지를 표시하기 위해 Activity를 사용하는 것은 너무 과하지 않나요???

 

 

 

 높은 점수를 받은 Solution 

Here I have created a simple Dialog, like:

여기서 간단한 대화 상자를 만들었습니다. 다음과 같이:

 

Dialog Box

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold"/>
    

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

 

You have to extends Dialog and implements OnClickListener

이것은 Dialog를 확장하고 OnClickListener를 구현해야합니다.
public class CustomDialogClass extends Dialog implements
    android.view.View.OnClickListener {

  public Activity c;
  public Dialog d;
  public Button yes, no;

  public CustomDialogClass(Activity a) {
    super(a);
    // TODO Auto-generated constructor stub
    this.c = a;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.custom_dialog);
    yes = (Button) findViewById(R.id.btn_yes);
    no = (Button) findViewById(R.id.btn_no);
    yes.setOnClickListener(this);
    no.setOnClickListener(this);

  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_yes:
      c.finish();
      break;
    case R.id.btn_no:
      dismiss();
      break;
    default:
      break;
    }
    dismiss();
  }
}

 

How to Call Dialog ?

다이얼로그를 호출하는 방법
R.id.TXT_Exit:
CustomDialogClass cdd=new CustomDialogClass(Values.this);
cdd.show();  

 

Updates

업데이트

 

After a long time one of my friends asked me to make a curved shape dialog with a transparent background. So, Here I have implemented it.

오랜만에 내 친구 중 한 명이 투명한 배경을 가진 곡선형 대화상자를 만들어 달라고 요청해줬습니다. 그래서 이를 구현해 보았습니다.

 

enter image description here

To Make a curved shape you need to create a separate curve_shap.XML as below,

곡선 모양을 만들려면 아래와 같이 별도의 curve\_shap.XML 파일을 만들어야합니다.
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#000000" />

    <stroke
        android:width="2dp"
        android:color="#ffffff" />

    <corners
        android:bottomLeftRadius="20dp"
        android:bottomRightRadius="20dp"
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp" />

</shape>

 

Now, add this curve_shap.XML in your main view Layout. In my case I have used LinearLayout

이제 이 curve\_shap.XML을 메인 뷰 레이아웃에 추가하세요. 저는 LinearLayout을 사용했습니다.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:background="@drawable/curve_shap"
        android:orientation="vertical" >
...
</LinearLayout>

 

How to call this ?

이걸 어떻게 호출하나요?
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();

 

I hope that works for you.

제가 작성한 코드가 도움이 되길 바랍니다.

 

 

 

 가장 최근 달린 Solution 

Here is a very simple way to create a custom dialog.

여기 매우 간단한 사용자 지정 대화 상자를 만드는 방법이 있습니다.

 

dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!--  Put your layout content  -->
</LinearLayout>

 

MainActivity.java

ShowPopup(){
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog, null);
android.app.AlertDialog.Builder alertDialogBuilder = new 
android.app.AlertDialog.Builder(this);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setCancelable(true);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}

 

 

출처 : https://stackoverflow.com/questions/13341560/how-to-create-a-custom-dialog-box-in-android

반응형
댓글
공지사항
최근에 올라온 글