본문 바로가기

구글과인터넷/안드로이드

안드로이드 팝업창 만들기

출처 : http://blog.naver.com/vortex2s?Redirect=Log&logNo=10102806271

안드로이드를 개발하다보면 Dialog같은 메시지 창을 자주 쓰게 되는데 기본으로 주어지는 것은 AlertDialog와 Toast밖에는....ㅠㅠ AlertDialog는 이쁘지 않고 몬가 불만족스럽고 Toast는 간단한 메시지를 띄워서 보여주기 좋은데..이것도 마찬가지로..ㅠㅠ불만이 많다..

 

개발을 하다보면 나만의 메시지창을 만들어 보고 싶다는 생각을 하게 되는데 그럴때를 위해 Popup View로 이쁘게 만들면^^나만의 메시지창을 띄울수 있다.

예제 소스와 간단한 주석으로 나만의 Popup View를 만들어 보자.

 

먼저 PopView를 생성하도록하자.

 

public class PopView {
   protected final View anchor;
   protected final PopupWindow window;
   private View root;
   private Drawable background = null;
   protected final WindowManager windowManager;
   public PopView(View anchor) {
      this.anchor = anchor;
      this.window = new PopupWindow(anchor.getContext());
      window.setTouchInterceptor(new OnTouchListener() {
         @Override
         public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { // popupview영역 외의 바깥부분을 터치할 시
               PopView.this.window.dismiss();
               return true;
            }
            return false;
         }
   });  

      windowManager = (WindowManager) anchor.getContext().getSystemService(Context.WINDOW_SERVICE);
      onCreate();
   }
   protected void onCreate() {}
   protected void onShow() {}
   protected void preShow() {
      if (root == null) {
         throw new IllegalStateException("IllegalStateException preShow.");
      }  
      onShow();
      if (background == null) {
         window.setBackgroundDrawable(new BitmapDrawable());
      } else {
         window.setBackgroundDrawable(background);
      }
      window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
      window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
      window.setTouchable(true);
      window.setFocusable(true);
      window.setOutsideTouchable(true);
      window.setContentView(root);
   }
   public void setBackgroundDrawable(Drawable background) {
       this.background = background;
   }
   public void setContentView(View root) {
      this.root = root;
      window.setContentView(root);
   }
   public void setContentView(int layoutResID) {
      LayoutInflater inflator = (LayoutInflater) anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      setContentView(inflator.inflate(layoutResID, null));
   }
   public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
      window.setOnDismissListener(listener);
   }
   public void dismiss() {
      window.dismiss();  // popupview를 닫는다.
   }

}

 

생성된 popupview를 상속받아서 동작할 class를 만든다.

 

public class Pop extends PopView{

   private final Context context;
   private final LayoutInflater inflater;
   private final View root;
   private ViewGroup mTrack;
 
   public Pop(View anchor) {
      super(anchor);  
      context  = anchor.getContext();
      inflater  = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      root  = (ViewGroup) inflater.inflate(R.layout.popview, null);
      setContentView(root);
      mTrack    = (ViewGroup) root.findViewById(R.id.viewRow); //팝업 View의 내용을 추가한 LinearLayout
   }

   public void show () {
      preShow(); //상속받은 PopView의 메서드

      int[] location   = new int[2];
      anchor.getLocationOnScreen(location);

      root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
      root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

      window.showAtLocation(this.anchor, Gravity.CENTER, 0, 0); //가운데 정렬 하여 보임
   }

}

 

이제 이렇게 되면 popview의 준비는 끝이네요~^^ 이제 xml의 구성을 보면 되겠죠.

먼저 popview가 되어질 xml입니다. 팝업되는 화면이죠.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content" android:layout_height="wrap_content">
   <ScrollView //임의적으로 view를 뿌려주기위해 가로 세로 200dip의 크기 efefef배경색으로 지정
      android:layout_width="200dip" android:layout_height="200dip"
      android:fadingEdgeLength="0dip" android:background="#ffefefef"
      android:scrollbars="none">
      <LinearLayout android:id="@+id/viewRow"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:paddingTop="2dip" android:paddingBottom="2dip"
         android:paddingLeft="10dip" android:paddingRight="10dip"
         android:orientation="vertical" />
   </ScrollView>
</LinearLayout>

 

이제 popview의 준비는 끝났고, 이벤트를 통해서 popview를 띄우도록 하겠습니다.

간단하게 버튼하나를 추가하고버튼을 클릭했을때의 이벤트를 받도록합니다.

@Override
public void onClick(View v) {
   Show(v);
}

Pop pop;
private void Show(View v){
   pop = new Pop(v);  
   pop.show();  //popview를 출력
}

 

이렇게 간단하게 view를 출력하면 간단한 팝업창이 나오게됩니다. 그냥 회색의 네모로 보이지만 xml로 이미지를 넣고 꾸미면 더 좋은 popview가 완성 됩니다.

 


 

다음번에는 이벤트와 텍스트등을 더 넣어 보겠습니다.


//////////////////////////////////////////////////////////////////////////////////////////

출처: http://snowbora.com/444


간단한 팝업 다이얼로그 띄우는 건 안드로이드에서 제공하는 AlertDialog을 이용하면 쉽게 구현할 수 있습니다.
하지만, 이 팝업 다이얼로그를 사용자 마음대로 바꾸고 싶을 때는
LayoutInflater 을 이용해서 사용자가 직접 만든 View를 생성해서 AlertDialog에 연결해서 보여줄 수 있습니다.


그 간단한 예는 다음과 같습니다.

01.private AlertDialog m_adlgConnectionInfo = null;
02. 
03.private void ShowConnectionInfoPopup()
04.{
05.if (m_adlgConnectionInfo != null)
06.{
07.m_adlgConnectionInfo.dismiss();
08.}
09. 
10.LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
11.View view = inflater.inflate(R.layout.comp_connected_device, null);
12.ImageView ivServer = (ImageView)view.findViewById(R.id.iv_con_server);
13.TextView tvServer = (TextView)view.findViewById(R.id.tv_con_server);
14.ImageView ivRender = (ImageView)view.findViewById(R.id.iv_con_render);
15.TextView tvRender = (TextView)view.findViewById(R.id.tv_con_render);
16. 
17.DMSContentItem dmsContentsItem = m_ImageGallery.GetDMCContentItem();
18.ivServer.setImageBitmap(AllShareMainData.getDeviceIcon(dmsContentsItem));
19.tvServer.setText(dmsContentsItem.getDeviceItem().getFriendlyName());
20.ivRender.setImageResource(R.drawable.dms_micro_hhp);
21.tvRender.setText("My Device");
22. 
23.m_adlgConnectionInfo = new AlertDialog.Builder(this)
24..setView(view)
25..setTitle("Connected devices")
26..setPositiveButton("OK"new DialogInterface.OnClickListener()
27.{
28.@Override
29.public void onClick(DialogInterface dialog, int which)
30.{
31.dialog.dismiss();
32.}
33.})
34..create();
35. 
36.m_adlgConnectionInfo.show();
37.}
맨 윗줄에 있는 m_adlgConnectionInfo이 null 이 아닌 경우 dismiss()를 호출하는 이유는
팝업 버튼을 연속으로 두 번 눌렀을 때 팝업창이 2개 뜨는 것을 방지하기 위한 코드입니다.
 

1.LayoutInflater를 이용해서 사용자 정의 View를 생성하는 것과 setView() 메소드를 이용해서 View를<br>
2.세팅해주는 것만 주의하면 어렵지 않게 구현할 수 있습니다. 

////////////////////////////////////////////////////////////////////////


출처: http://blog.naver.com/PostView.nhn?blogId=eunsang5&logNo=100116312397

package popup.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;

public class PopupTest extends Activity {
 
 protected static final int DIALOG_SIMPLE_MESSAGE = 0;
 protected static final int DIALOG_YES_NO_MESSAGE = 1;
 protected static final int DIALOG_CHOICE_MESSAGE = 2;
 protected static final int DIALOG_PROGRESS_MESSAGE = 3;
 
 
 private Button simple;
 private Button yesno;
 private Button choice;
 private Button progress;
 private int mProgress;
 private Handler mProgressHandler;
 
 ProgressDialog mProgressDialog;


 
 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        simple = (Button) findViewById(R.id.simple);
        yesno = (Button) findViewById(R.id.yesno);
        choice = (Button) findViewById(R.id.choice);
        progress = (Button) findViewById(R.id.progress);
        
        simple.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
          showDialog(DIALOG_SIMPLE_MESSAGE);
         }
        });
        yesno.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
          showDialog(DIALOG_YES_NO_MESSAGE);
         }
        });
        
        choice.setOnClickListener(new OnClickListener() {
         public void onClick(View v){
          showDialog(DIALOG_CHOICE_MESSAGE);
         }
        });
        
        progress.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
          showDialog(DIALOG_PROGRESS_MESSAGE);
          mProgress=0;
          mProgressDialog.setProgress(0);  //progress의 초기값을 0으로
          mProgressHandler.sendEmptyMessage(0);
         }
        });
        
        mProgressHandler = new Handler(){
         public void handleMessage(Message msg){ //핸들러에서 메시지를 받기 위해서 반드시 이 함수를 구현해야 함.
          super.handleMessage(msg);
          if( mProgress >= 100 ){
           mProgressDialog.dismiss();
          }
          else{
           mProgress++;
           mProgressDialog.incrementProgressBy(1); //progressbar를 1씩 증가
           mProgressHandler.sendEmptyMessageDelayed(0, 100); //100ms후에 0이라는 값을 보냄
          }
         }
        };
    }
    
    protected Dialog onCreateDialog(int id){ //ShowDialog에서 인자로 넘긴 아이디값이랑 동일
     switch(id){
     case DIALOG_SIMPLE_MESSAGE :
      Dialog d = new Dialog(PopupTest.this);
      Window window = d.getWindow();
      window.setFlags(WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW,WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW);
      d.setTitle("hi");
      d.show();
      return d;
     
     case DIALOG_YES_NO_MESSAGE:
      return new AlertDialog.Builder(PopupTest.this)
      .setIcon(R.drawable.icon)
      .setTitle("Yes/No Dialog")
      .setMessage("do you know me?")
      .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    
    public void onClick(DialogInterface dialog, int which) {
     // TODO Auto-generated method stub
     
    }
   })
   .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
    
    public void onClick(DialogInterface dialog, int which) {
     // TODO Auto-generated method stub
     
    }
   })
   .create();
      
      
     case DIALOG_CHOICE_MESSAGE:
      return new AlertDialog.Builder(PopupTest.this)
      .setIcon(R.drawable.icon)
      .setTitle("Single Choice")
      //.setSingleChoiceItems(R.array.select_dialog_item2, 0, new DialogInterface.OnClickListener(){
     //  public void onClick(DialogInterface dialog, int whichButton){
     //   
     //  }
     /s/ })
      .setPositiveButton("OK", new DialogInterface.OnClickListener(){
       public void onClick(DialogInterface dialog, int whichButton){
        
       }
      })
      .setNegativeButton("CANCEL", new DialogInterface.OnClickListener(){
       public void onClick(DialogInterface dialog, int whichButton){
        
       }
      })
      .create();
      
     }//switch
    
    return super.onCreateDialog(id);    
        
    }  
}

 

 

 

*******main.xml***********

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
 android:id="@+id/simple" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Simple Dialog"
 />
 <Button
 android:id="@+id/yesno" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Yes/No Dialog"
 />
 <Button
 android:id="@+id/choice" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Single Choice Dialog"
 />
 <Button
 android:id="@+id/progress" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Progress Dialog"
 />
</LinearLayout>

 

 

 

http://sje0114121.blog.me/150089055388

 

 

http://blog.naver.com/hhl0517?Redirect=Log&logNo=60110794557&jumpingVid=DDDB7BFBA2430682181E675B389FA5C322ED

 

 

 

http://developer.android.com/reference/android/app/ListActivity.html

 

 

http://underclub.tistory.com/308


/////////////////////////////////////////////////////////////


출처: http://ememomo.tistory.com/3



첫 블로그를 개설해서 무엇을 올릴까 생각하다가, 최근에 만들던 윈도우 팝업을 먼저 올려 봅니다. ㅎ

Dialog 와는 다르게 위치와 모양부분에서 포퍼먼스가 조금더 좋다고 생각하는데요, 물론 개인적인 입장입니다.

Dialog도 꾸미게 되면 얼마든지 이쁘게 꾸밀 수 있겠죠.

서두는 그만 두고 본론으로 들어 가도록 하겠습니다.

Layout 부분 입니다. 팝업으로 만들 부분에 대해 레이아웃을 따로 지정해 줍니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:orientation="vertical"
 android:id="@+id/linear"
 android:background="@drawable/xxxxx"   // 따로 지정할 배경이미지를 만든부분 입니다.
 android:layout_height="wrap_content">
 <RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <ImageView
   android:layout_width="120dip"
   android:layout_height="120dip"
   android:id="@+id/img"
   android:layout_marginLeft="5dip"
   android:layout_marginTop="5dip"
   android:layout_marginRight="5dip"
   android:layout_alignParentLeft="true" />
  <TextView
   android:id="@+id/name"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="5dip"
   android:text="홍길동"
   android:textSize="25dip"
   android:layout_toRightOf="@id/img" />
  <TextView
   android:id="@+id/hiwords"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_below="@id/name"
   android:layout_marginTop="5dip"
   android:textSize="15dip"
   android:layout_alignLeft="@id/name" />
  <ImageButton
   android:id="@+id/exit"
   android:background="@drawable/fd_am_delete_btn_s"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentRight="true" />
  <Button
   android:id="@+id/two_btnLeft"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="1:1채팅"
   android:textSize="15dip"
   android:layout_centerHorizontal="true"
   android:layout_marginLeft="20dip"
   android:layout_alignParentLeft="true"
   android:layout_alignParentBottom="true"
   android:layout_below="@id/img" />
  <Button
   android:layout_marginLeft="7dip"
   android:layout_centerHorizontal="true"
   android:id="@+id/two_btnRight"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textSize="15dip"
   android:layout_marginRight="20dip"
   android:layout_alignParentRight="true"
   android:layout_alignParentBottom="true"
   android:layout_below="@id/img"
   android:text="RIGHT" />
 </RelativeLayout>
</LinearLayout>


이 레이아웃 화면 구성입니다. 








이미지 부분 과 타이틀 / 종료 버튼 / 서브 타이틀 /
버튼 두개로 구성한 상태입니다.

띄울때의 코드 부분입니다. 
리스트목록에서 해당 행을 선택했을대 윈도우 팝업이 뜨도록 하였습니다. 

따로 만든게 아니고 프로젝트에 들어가있는 코드라 팝업부분만 보이도록 하겠습니다 ^^;;

public class MemberListActivity extends Activity implements OnItemClickListener, OnTouchListener {
 

 ListView arr_list;
 
 LinearLayout linear;  // 팝업의 레이아웃 id
 View popupview;
 PopupWindow popup;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.memberlist);
  
//  Log.d("myprofile_id", myprofile.getProf_id());
  myprofile = NootoGlobal.getPHONE();
  
 popupview = View.inflate(this, R.layout.popup_profile, null);
  popup = new PopupWindow(popupview, LayoutParams.FILL_PARENT, 270, true);
  popup.setOutsideTouchable(true); // 이부분을 설정해주어야 팝업이 떳을때 다른부분에 이벤트를 줄수있습니다.
  popup.setBackgroundDrawable(new BitmapDrawable());  // 이부분에 이벤트가 들어오게됩니다.
  
 }

//아이템을 클릭했을때 팝업을 띄워주는 부분입니다.  

 @Override
 public void onItemClick(AdapterView<?> arg0, View arg1, int position,
   long arg3) {
  popup.showAtLocation(arg1, Gravity.BOTTOM | Gravity.CENTER, 0, 0);
//  LinearLayout linear = (LinearLayout) View.inflate(
//    MemberListActivity.this, R.layout.popup_profile, null);
// 지정한 레이아웃을 가져옵니다.
// 각각의 팝업마다 들어갈 이미지와 타이틀 / 서브타이틀~ 
  ImageView imageView = (ImageView) popupview.findViewById(R.id.img);
  TextView name = (TextView) popupview.findViewById(R.id.name);
  TextView hiwords = (TextView) popupview.findViewById(R.id.hiwords);
  Button btnleft = (Button) popupview.findViewById(R.id.two_btnLeft);
  Button btnrigth = (Button) popupview.findViewById(R.id.two_btnRight);
  ImageButton exit = (ImageButton)popupview.findViewById(R.id.exit);
  phonenum = list.get(position).getProf_phone();
  DrawImage.imgDisp(imageView, list.get(position).getProf_img());
  name.setText(list.get(position).getProf_name());
  hiwords.setText(list.get(position).getProf_hiword());
  btnrigth.setText(list.get(position).getProf_phone());
//  
//  //종료 버튼 
//팝업 dismiss 종료 눌렀을때 팝업이 사라지게~
  exit.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    popup.dismiss();
   }
  });
//  
//  
//  
//  //전화 걸기
  btnrigth.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    startActivity(new Intent(Intent.ACTION_CALL,
      Uri.parse("tel:"+ phonenum)));
    popup.dismiss();
   }
  });
  index = position;
//  
//  //채팅방 입장
  btnleft.setOnClickListener(new OnClickListener() {
   
 // 생략합니다.
//  new AlertDialog.Builder(MemberListActivity.this).setView(linear).show();

 }

  
 완성된 화면입니다.