In Android development, it is often necessary to click on a button pop-up dialog box or selection box, through dialog or PopupMenu, Popupwindow can be achieved.
Here mainly introduces the latter two: PopupMenu, Popupwindow realization. First look at the top of the two effects popupmenu, the bottom Popupwindow:
PopupMenu Popupwindow
First, PopupMenu implementation:
PopupMenu is simpler to implement, and is mainly used to implement dialog boxes that pop up near a button.
First, define a menu file \res\menu\headmenu.xml:
<menu xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:app= "http://schemas.android.com/ Apk/res-auto "
xmlns:tools=" Http://schemas.android.com/tools "tools:context=" com.arbo.hero.LoginActivity " >
<item
android:id= "@+id/camera"
android:title= "photo"
android:orderincategory=
" app:showasaction= "Never"/> <item android:id= "@+id/gallery" android:title= "
Select from album"
android:orderincategory= "app:showasaction=" "
never"/> <item android:id= "
@+id/cancel"
android:title= "Cancel"
android:orderincategory= "app:showasaction="
never "/>
</menu >
Create a PopupMenu and add a click event:
private void Showpopmenu (view view) {
PopupMenu = new PopupMenu (this,view);
Popupmenu.getmenuinflater (). Inflate (R.menu.headmenu,popupmenu.getmenu ());
Popupmenu.setonmenuitemclicklistener (New Popupmenu.onmenuitemclicklistener () {
@Override public
Boolean Onmenuitemclick (MenuItem Item) {
switch (Item.getitemid ()) {case
R.id.camera:
toast.maketext ( Headportrait.this, "Click Camera", Toast.length_short). Show ();
break;
Case R.id.gallery:
toast.maketext (Headportrait.this, "click Gallery", Toast.length_short). Show ();
break;
Case R.id.cancel:
toast.maketext (Headportrait.this, "Click Cancel", Toast.length_short). Show ();
break;
return false;
}
});
Popupmenu.show ();
}
Mainactivity is very simple, click the button call Showpopmenu () method can:
public class Mainactivity extends activity{
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Main.xml page main layout has only one button, here is no code
Setcontentview (r.layout.main);
Button button = (button) Findviewbyid (R.id.button);
Button.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick (view view) {
// Click on the button to create and display a PopupMenu
showpopmenu (Btnmenu);}}}
Above, it realizes using PopupMenu to pop a selection box near the button.
PopupMenu Advantages: Simple, according to the menu size adaptive position, pop-up near the button, suitable for some scenarios.
Disadvantage: The form is relatively unitary, the effect is general.
Second, Popupwindow implementation:
By contrast, the Popupwindow implementation is more complex, but more customizable, and it can set any interface to Popupwindow.
First look at the pop-up window layout window_popup.xml:
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:layout_marginleft=" @ Dimen/activity_horizontal_margin "android:layout_marginright=" @dimen/activity_horizontal_margin "Android:
Background= "#dadada" android:orientation= "vertical" > <linearlayout android:layout_width= "match_parent"
android:layout_height= "wrap_content" android:orientation= "vertical" > <button android:id= "@+id/camera" Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "photographed" android:background= "# F0f0f0 "/> <textview android:layout_width=" match_parent "android:layout_height=" 1DP "android:background=" #2 d2c2c "/> <button android:background=" #f0f0f0 "android:id=" @+id/gallery "android:layout_width=" match_parent "Android:layout_height=" Wrap_content "android:text=" from mobile phone album selection "/> <tExtview android:layout_width= "match_parent" android:layout_height= "1DP" android:background= "#2d2c2c"/> <Bu Tton android:background= "#f0f0f0" android:id= "@+id/savepicture" android:layout_width= "Match_parent" android:layout _height= "Wrap_content" android:text= "Save Picture"/> </LinearLayout> <linearlayout android:layout_width= "match _parent "android:layout_height=" wrap_content "android:layout_margintop=" 10DP "android:orientation=" vertical "> & Lt Button android:background= "#f0f0f0" android:id= "@+id/cancel" android:layout_width= "Match_parent" android:layout_he
ight= "Wrap_content" android:text= "Cancel"/> </LinearLayout> </LinearLayout>
Layout Effect Chart:
To create a Popupwindow and add a click event for it:
void Bottomwindow (view view) {
if (Popupwindow!= null && popupwindow.isshowing ()) {return
;
}
LinearLayout layout = (linearlayout) getlayoutinflater (). Inflate (r.layout.window_popup, null);
Popupwindow = new Popupwindow (layout,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_ CONTENT);
When clicking on the blank, Hide pop window
popupwindow.setfocusable (true);
Popupwindow.setbackgrounddrawable (New bitmapdrawable ());
Add pop-up, bouncing animation
Popupwindow.setanimationstyle (R.style.popupwindow);
int[] location = new Int[2];
View.getlocationonscreen (location);
Popupwindow.showatlocation (view, Gravity.left | Gravity.bottom, 0,-location[1]);
Add key Event Monitor
setbuttonlisteners (layout);
Add Pop window Shutdown event, mainly the transparency
Popupwindow.setondismisslistener (New Popondismisslistener ()) that changes the background when it is closed;
Backgroundalpha (1f);
}
Event Listener Functions setbuttonlisteners ():
private void Setbuttonlisteners (LinearLayout layout) {button camera = (Button) Layout.findviewbyid (R.id.camera);
Button gallery = (button) Layout.findviewbyid (r.id.gallery);
Button SavePicture = (button) Layout.findviewbyid (r.id.savepicture);
button Cancel = (Button) Layout.findviewbyid (R.id.cancel); Camera.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {if Popupwindow!=
Null && popupwindow.isshowing ()) {//Add your key to handle XXX Popupwindow.dismiss () here;
}
}
}); Gallery.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {if Popupwindow!
= null && popupwindow.isshowing ()) {//Add your key to handle XXX Popupwindow.dismiss () here;
}
}
}); Savepicture.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {if Popupwind
ow!= null && popupwindow.isshowing ()) {//Add your key to handle XXX Popupwindow.dismiss () here;
}
}
}); CanCel.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {if Popupwindow!= nu
ll && popupwindow.isshowing ()) {Popupwindow.dismiss ();
}
}
});
}
Pop-up, retracted animation:
If there is no Anim directory under the Res folder, add one yourself: New–>android Resource Directory name to fill Anim. Then create a new two tranlate file:
Pop-up window_out.xml:
<?xml version= "1.0" encoding= "Utf-8"?> <translate xmlns:android=
"http://schemas.android.com/apk/res/" Android "
android:interpolator=" @android: Anim/decelerate_interpolator "
android:fromydelta=" 100% "Android" : Toydelta= "0"
android:duration= "/>"
Retract Window_back.xml:
<?xml version= "1.0" encoding= "Utf-8"?> <translate xmlns:android=
"http://schemas.android.com/apk/res/" Android "
android:interpolator=" @android: Anim/accelerate_interpolator "
android:fromydelta=" 0 "Android: Toydelta= "100%"
android:duration= "/>"
Then add our two animations to the Style.xml:
<style name= "Popupwindow" >
<item name= "android:windowenteranimation" > @anim/window_out</item >
<item name= "android:windowexitanimation" > @anim/window_back</item>
</style>
Or the top of the same mainactivity, the button click on the event to replace the processing function Popupwindow can:
Btnmenu.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick (view view) {
Bottomwindow (Btnmenu);
}
Above, you can implement such a click button from the bottom of the screen pop-up window effect, as follows:
Bottom Eject
However, this is not a good effect, we want to pop windows, other backgrounds can be translucent, so you can highlight the focus. The online approach is to use this code to change the transparency of the background:
/**
* Settings Add screen background transparency
* @param bgalpha *
/public void Backgroundalpha (float bgalpha)
{
Windowmanager.layoutparams LP = GetWindow (). GetAttributes ();
Lp.alpha = Bgalpha; 0.0-1.0
GetWindow (). SetAttributes (LP); GetWindow (). Addflags (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Then set the background to translucent when it pops up:
Bottomwindow (Btnmenu);
Backgroundalpha (0.5f);
Set back at the time of return:
Backgroundalpha (1f);
This is true to achieve results, but when clicked suddenly dimmed and brightened, the effect is not very good! As follows:
I want to be ejected from the process and slowly darken. There is a process, not a sudden dark down. This uses latency and handler to dynamically change the transparency of the background.
After invoking the pop-up method, open a child thread
@Override public
void OnClick (view view) {
Bottomwindow (btnmenu);
New Thread (New Runnable () {
@Override public
void Run () {while
alpha>0.5f) {
try {
// 4 is computed Thread.Sleep (4) based on pop-up animation time and reduced transparency
;
} catch (Interruptedexception e) {
e.printstacktrace ();
}
Message msg =mhandler.obtainmessage ();
Msg.what = 1;
0.01 reduction each time, the higher the precision, the more smooth the effect of dimming
alpha-=0.01f;
Msg.obj =alpha;
Mhandler.sendmessage (msg);}}}
). Start ();
}
Likewise, return the transparency by jumping back:
/**
* When returning or clicking on a blank position, change the background transparency back to */
class Popondismisslistener implements popupwindow.ondismisslistener{
@Override public
void Ondismiss () {
//TODO auto-generated method stub
New Thread (new Runnable () {
@Override public
Void Run () {
//here while the condition Alpha cannot <= otherwise a black screen while
(alpha<1f) {
try {
Thread.Sleep (4);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
LOG.D ("headportrait", "Alpha:" +alpha);
Message msg =mhandler.obtainmessage ();
Msg.what = 1;
alpha+=0.01f;
Msg.obj =alpha;
Mhandler.sendmessage (msg);}}}
). Start ();
}
In handler we call the method that changes the background transparency:
Handler Mhandler = new Handler () {
@Override public
void Handlemessage (msg) {
switch (msg.what) { C33/>case 1:
Backgroundalpha ((float) msg.obj);
break;
}
}
;
After this modification, the effect is this:
Above, basically reached the gradual dimming, variable purpose.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.