読者です 読者をやめる 読者になる 読者になる

liguofeng29’s blog

個人勉強用ブログだっす。

AndroidのUI - PopupWindow

 

activity_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="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button android:id="@+id/showbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show POPUP"
/>
</LinearLayout>
 
popup.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<ImageView
android:layout_width="240dp"
android:layout_height="wrap_content"
android:src="@drawable/hehe"
/>
<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关闭"
/>
</LinearLayout>
   
MainActivity.java
 
package com.example.liguofeng.popupwindow;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

View root = this.getLayoutInflater().inflate(R.layout.popup, null);

final PopupWindow pop = new PopupWindow(root, 560, 720);
Button showBtn = (Button) findViewById(R.id.showbtn);
showBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pop.showAsDropDown(v);
pop.showAtLocation(findViewById(R.id.showbtn), Gravity.CENTER, 20, 20);
}
});

// POP中のボタン
root.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pop.dismiss(); // POPUP閉じる
}
});
}
}