MainActivity.java
package com.example.android.popwindow;
import com.example.android.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;
public class MainActivity extends Activity {
PopupWindow pw = null;
boolean isClicked = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_main);
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pw = new PopupWindow(inflater.inflate(R.layout.pop_content,
null, false), 100, 100, true);
pw.setFocusable(false);
}
public void onClickBtn(View v){
if(isClicked == true){
pw.dismiss();
isClicked = false;
}else if(isClicked == false){
pw.showAsDropDown(this.findViewById(R.id.pop_btn));
isClicked = true;
}
}
}
We can use
showAtLocation to replace the showAsDropDown. Because this method is
more flexibile than the prior one.
res/layout/pop_content.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Content"
/>
</LinearLayout>
res/layout/pop_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/pop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="onClickBtn"
/>
</LinearLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="14" />
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@style/AppTheme">
<activity android:name="com.example.android.popwindow.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Reference:
Android Developer Guide