ポップアップウィンドウを表示する |
ここでは、ポップウィンドウを表示する方法を確認します。
ポップアップウィンドウを表示するには「showAsDropDown」メソッドを使用します。 ポップアップウィンドウを表示する流れとしては以下のようになります。 1.「LayoutInflater」インスタンスを取得する。 2.「onflate」メソッドを使用して「popup.xml」を取得する。 3.「PopupWindow」インスタンスを生成する。 4.「setContentView」メソッドでpopupViewをセットする。 5.ポップアップのサイズ(幅、高さ)を設定する。 6.ボタンにリスナーを設定する。 PopupActivity.java package goodroid.sample.popup; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.PopupWindow; public class PopupActivity extends Activity implements OnClickListener{ PopupWindow popupWindow; Handler mHandler = new Handler(); View view; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // LayoutInflaterインスタンスを取得 LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); // ポップアップ用のViewをpopupxmlから読み込む View popupView = (View)inflater.inflate(R.layout.popup, null); // レイアウトパラメータをセット popupView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); // PopupWindowを紐づけるViewのインスタンスを取得 view = findViewById(R.id.button); // viewに紐づけたPopupWindowインスタンスを生成 popupWindow = new PopupWindow(view); // ポップアップ用のViewをpopupWindowにセットする popupWindow.setContentView(popupView); // サイズ(幅)を設定 popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); // サイズ(高さ)を設定 popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); // 切替ボタンにリスナーを設定 Button btn = (Button) findViewById(R.id.button); btn.setOnClickListener(this); } public void onClick(View v){ // 切替ボタン押下時にポップアップウィンドウの表示、非表示を切り替える if(popupWindow.isShowing()){ popupWindow.dismiss(); }else{ popupWindow.showAsDropDown(view, 0, 0); } } } main.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="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ポップアップ切替スイッチ" /> </LinearLayout> ★レイアウトファイル (ポップアップ用) popup.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="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="ポップアップウィンドウに表示された文章です。" /> </LinearLayout> 実行結果 ![]() ![]() |
20946 views | コメント:0 | 2012-06-09 |
コメント
|
|
まだこの記事にコメントはありません |