استفاده از پنجره ی popup در اندروید
چهارشنبه 6 آبان 1394در این مقاله قصد داریم در مورد پنجره ی popup در اندروید صحبت کنیم ، این که چگونه می توان یک پنجره ی با زدن دکمه باز و بسته شود.
یک xml جدید به نام popup بسازید وقطعه کد زیر را داخل آن بنویسید:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@android:color/background_light"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_margin="1dp" android:background="@android:color/darker_gray"> > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_margin="20dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="پنجره popup" /> <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/bar" /> <Button android:id="@+id/dismiss" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="بستن popup" /> </LinearLayout> </LinearLayout> </LinearLayout>
از یک Text و یک ImageView برای نمایش عکس و یک دکمه برای باز و بسته شدن استفاده شده است.
حالا داخل کلاس جاوا قطعه کد زیر را بنویسید:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button btnOpenPopup = (Button)findViewById(R.id.openpopup); btnOpenPopup.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { LayoutInflater layoutInflater = (LayoutInflater)getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE); View popupView = layoutInflater.inflate(R.layout.popup, null); final PopupWindow popupWindow = new PopupWindow( popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss); btnDismiss.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub popupWindow.dismiss(); }}); popupWindow.showAsDropDown(btnOpenPopup, 50, -30); }}); }
دکمه ای که تعریف کرده بودیم در xml داخل کلاس جاوا برای آن یک رویداد OnClickListner می نویسیم
و عکسی که قرار است نمایش داده شود که داخل ImageView قرار داده بودیم را popupview تعریف می کنیم.
اگر میخواهید کل صفحه را بگیرد از math_Parent استفاده کنید ولی برای اینکه زیباتر به نظر بیاید از wrap_Content استفاده می کنیم.
در آخر دکمه ی بسته شدن popup را تعریف می کنیم و رویداد دکمه را برای آن می نویسیم.
و برای اینکه پنجره ی popup مناسبی قرار بگیرد می توانید از قطعه کد زیر استفاده نمایید و با توجه به نیازتان هر کجای صفحه که دوست داشتید قرار دهید.
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
خروجی به صورت زیر خواهد شد:
- Android
- 2k بازدید
- 2 تشکر