實例:
修改main.xml, 添加一個按鈕用來打開彈出視窗(PopupWindow).
<?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="@string/hello" />
<Button
android:id="@+id/openpopupwindow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Open PopupWindow" />
</LinearLayout>
主要的Java代碼.
package com.PopupWindow;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
public class PopupWindowActivity extends Activity {
Button buttonOpen;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonOpen = (Button)findViewById(R.id.openpopupwindow);
buttonOpen.setOnClickListener(buttonOpenOnClickListener);
}
Button.OnClickListener buttonOpenOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View view) {
openPopupWindow(view);
}};
private void openPopupWindow(View v){
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 buttonClose = (Button)popupView.findViewById(R.id.closepopupwindow);
buttonClose.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(buttonOpen);
popupWindow.setFocusable(true);
popupWindow.update();
}
}
創建/res/layout/popup.xml文件, 定義彈出視窗的佈局.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#000055">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PopupWindow" />
<Button
android:id="@+id/closepopupwindow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
請教您,那要如何關閉呢?
回覆刪除popupWindow.dismiss()
刪除