I use following code to show a small popup:
public static PopupWindow showImportMenu(Activity activity, View anchor, PopupWindowClickListener onClickListener)
{
LayoutInflater inflater = LayoutInflater.from(activity);
PopupImportBinding binding = DataBindingUtil.inflate(inflater, R.layout.popup_import, null, false);
if (!RootTools.isRootAvailable())
binding.llImportRootMethod.setVisibility(View.GONE);
PopupWindow popupWindow = new PopupWindow(activity, null, R.attr.popupMenuStyle);
popupWindow.setFocusable(true);
popupWindow.setContentView(binding.getRoot());
popupWindow.setOutsideTouchable(true);
PopupWindowCompat.showAsDropDown(popupWindow, anchor, 0, 0, Gravity.BOTTOM);
View.OnClickListener clickListener = new View.OnClickListener()
{
#Override
public void onClick(View view)
{
onClickListener.onClick(popupWindow, view);
}
};
binding.llImportDefault.setOnClickListener(clickListener);
binding.llImportRootMethod.setOnClickListener(clickListener);
binding.llImportHTCFromContacts.setOnClickListener(clickListener);
binding.llImportManual.setOnClickListener(clickListener);
return popupWindow;
}
This works on a lot of devices but on some rare devices it does not work, like:
Android 5.1.1 root slim rom
maybe others... until now, I don't know more about other devices
I got the feedback that no popup is shown. Does anyone know why this is not working on the above mentioned device? And what I can do to make it work on this device as well?
EDIT
It seems like it's not clear that what I want is following:
use showAsDropDown not showAtLocation or similar, I never saw this problem with showAtLocation yet
my solution is working on nearly all devices, it seems to be a phone/rom specific problem, maybe it's not even solvable as it COULD be a bug in the device as well => if someone knows of such a bug, telling me would be fine as well
I don't want to use a dialog (or anything else) instead, that's not answering my question. I currently use a BottomSheet which is fine for me, but still I would like to know if the problem can be solved and somehow handled
I got the same problem on a Nexus 7 (not 2012) running the 5.1.1. It is finally fixed by adding this line:
popupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
I was having the same problem: my PopupWindow was not showing on my 5.1.1 android device but it was on others. I realised that I had to specify the width and height in order to be shown on that version (which is still compatible with the rest of the versions as well).
Here is an example:
popUp.setWidth(MATCH_PARENT);
popUp.setHeight(WRAP_CONTENT);
In my case, popup window have no sizes on few devices.
Try that after setContentView
50000 - just a big size for measure.
popupWindow.getContentView().measure(50000, 50000);
popupWindow.setWidth(popupWindow.getContentView().getMeasuredWidth());
popupWindow.setHeight(popupWindow.getContentView().getMeasuredHeight());
You can use screen size instead 50000
Some ROMs restrict usage of popupview with their own permissions. So user have to explicitly turn on permission to show pop up views.
Even MIUI will restrict popupview to be displayed by default.
Please have a look whether there is any permission in that ROMs or devices.
Try QuickAction
Activity (ExampleActivity1.java) to show how to use QuickAction:
public class Example1Activity extends Activity {
private static final int ID_ADD = 1;
private static final int ID_ACCEPT = 2;
private static final int ID_UPLOAD = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example1);
ActionItem addItem = new ActionItem(ID_ADD, "Add", getResources().getDrawable(R.drawable.ic_add));
ActionItem acceptItem = new ActionItem(ID_ACCEPT, "Accept", getResources().getDrawable(R.drawable.ic_accept));
ActionItem uploadItem = new ActionItem(ID_UPLOAD, "Upload", getResources().getDrawable(R.drawable.ic_up));
//use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
uploadItem.setSticky(true);
final QuickAction mQuickAction = new QuickAction(this);
mQuickAction.addActionItem(addItem);
mQuickAction.addActionItem(acceptItem);
mQuickAction.addActionItem(uploadItem);
//setup the action item click listener
mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction quickAction, int pos, int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
if (actionId == ID_ADD) {
Toast.makeText(getApplicationContext(), "Add item selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), actionItem.getTitle() + " selected", Toast.LENGTH_SHORT).show();
}
}
});
mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Ups..dismissed", Toast.LENGTH_SHORT).show();
}
});
Button btn1 = (Button) this.findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuickAction.show(v);
}
})
Button btn2 = (Button) this.findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mQuickAction.show(v);
mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
}
});
}
}
Output:
(source: unitid.nl)
## Ok i implemented popupwindow for sorting in my tab fragment and i checked working fine once try this
I used in that custom layout for popup window
final PopupWindow popupWindow = new PopupWindow(getActivity());
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.popmenu1t1, null);
l8[![enter image description here][1]][1] = (LinearLayout) view.findViewById(R.id.atoz);
l8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
date_sort="0";
discount_sort="";
price_sort="";
alpha_sort="";
popupWindow.dismiss();
}
});
int width = 900;
int height = 400;
try {
WindowManager wm = (WindowManager)view.getContext().getSystemService(Context.WINDOW_SERVICE);
width = wm.getDefaultDisplay().getWidth();
height = wm.getDefaultDisplay().getHeight();
} catch (Exception e) {
e.printStackTrace();
}
popupWindow.setWidth(width*3/6);
popupWindow.setFocusable(true);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(view);
popupWindow.setBackgroundDrawable(null);
popupWindow.setOutsideTouchable(true);
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
Find the below attached screen shot popupwindow in my app
I had created a custom popup dialog shows at bottom of screen
public class MoreOptionDialog {
private Dialog dialog;
private Context context;
private int size;
public MoreOptionDialog(Context context) {
this.context = context;
}
public void showMoreOptionDialog(List<String> listMoreOption) {
dialog = new Dialog(new ContextThemeWrapper(context, R.style.DialogSlideAnim));
dialog.getWindow().setWindowAnimations(R.style.DialogSlideAnim);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View view = View.inflate(context, R.layout.dialog_more_option, null);
dialog.setContentView(view, new LinearLayout.LayoutParams(utility.getScreenWidth() - 100, size));
dialog.getWindow().setGravity(Gravity.BOTTOM);
ListView listView = (ListView) view.findViewById(R.id.lvMoreOption);
MoreOptionAdapter moreOptionAdapter = new MoreOptionAdapter(context, listMoreOption, Gravity.CENTER);
listView.setAdapter(moreOptionAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
dialog.dismiss();
}
});
dialog.show();
}
}
And style is here
<style name="DialogSlideAnim">
<item name="android:windowAnimationStyle">#style/DialogAnimation</item>
<item name="android:windowBackground">#color/color_white</item>
<item name="android:windowFrame">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
</style>
And this dialog working in all devices :)
Related
Here is some brief codes of my project, in which I'd like to display a Unity3D model to do something.
public class MainActivity extends FragmentActivity{
protected UnityPlayer mUnityPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getWindow().setFormat(PixelFormat.RGBX_8888);
mUnityPlayer = new UnityPlayer(this);
...
mTestImageButton = ***;
mTestImageButton.setOnClickListener(mTestImageButtonClickListener);
}
private ImageButton mTestImageButton;
private View.OnClickListener mTestImageButtonClickListener = new
View.OnClickListener() {
#Override
public void onClick(View v) {
showUnity3D_dialog(v);
//showUnity3D_popupwindow(v);
}
};
private void showUnity3D_dialog(View v) {
Dialog dialog = new Dialog(v.getContext(), R.style.move_dialog);
dialog.setContentView(mUnityPlayer);
Window window = dialog.getWindow();
window.setWindowAnimations(R.style.move_dialog);
WindowManager.LayoutParams lp = window.getAttributes();
window.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
lp.width = 1179;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
window.setAttributes(lp);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
dialog.setCanceledOnTouchOutside(true);
dialog.show();
mUnityPlayer.resume();
}
private void showUnity3D_popupwindow(View v) {
PopupWindow pop = new PopupWindow(mUnityPlayer, 1000, 800);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);
pop.setOutsideTouchable(false);
pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
}
});
pop.showAtLocation(v, Gravity.BOTTOM, 0, 0);
mUnityPlayer.resume();
}
}
As codes above, I tried to display a Unity3D-model in a PopupWindow, but the result makes me a bit confused, since there is nothing on screen when I called showUnity3D_popupwindow(v).
But when I called showUnity3D_dialog(v), the model by Unity3D shows.
I really can't understand what caused such scenario, and how can I display my model in a PopupWindow in android? Or, is it an impossible task?
I have my project under Android 4.3 & Unity 5.4.0.
Thanks a lot.
Looks like you are currently using the PopupWindow(View contentView, int width, int height) overload function. I've seen instances where functions that take View, Context or Activity does not work in Unity and you have to try other overloads.
You've tried the one takes View, now try the Context overload:
PopupWindow(Context context)
then set the width and height later on with the setWidth and setHeight function. You can get the current Context with UnityPlayer.currentActivity.getApplicationContext().
private void showUnity3D_popupwindow(View v)
{
Context mContext = UnityPlayer.currentActivity.getApplicationContext();
PopupWindow pop = new PopupWindow(mContext);
pop.setWidth(1000);
pop.setHeight(800);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);
pop.setOutsideTouchable(false);
pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
}
});
pop.showAtLocation(v, Gravity.BOTTOM, 0, 0);
mUnityPlayer.resume();
}
Context: There is a custom Listview and each list item has a button in it. When you click the button an alertDialog appears with an edit text and submit button. This only happens on the first click, on subsequent clicks a Toast will simply appear with the number of times it has been clicked thus far.
When you click the submit button a toast will appear displaying the text that was entered into the editText and the number of times they have clicked on it which will presumably always be 1 since this can only happen on the first click.
Problem: The timesClicked counter is not working properly if the user so much as clicks on the editText before clicking submit. It is restting to 0 I guess. However if the user does not click on the editText then the program works normally. 0_o I'm at a loss.
Attempts at solving: I simplified the code down quite a bit to try and pinpoint the problem and this is where I am stuck. Originally I was inflating a view that only had an edit text and then I was just using builder.setPositiveButtton. I thought implementing the buttons directly in the view would fix it but that doesn't seem to be the case. I have been stuck on this for awhile. Any help would be great
Here is a video of the bug happening
private class OnSubtractClickListener implements View.OnClickListener {
final int id; //id of list item that was clicked
int timesClicked;
Toast toast;
public OnSubtractClickListener(int id, View view) {
super();
this.id = id;
timesClicked = 0;
}
#Override
public void onClick(View view) {
if (timesClicked != 0) {
toast.setText(Integer.toString(timesClicked));
toast.show();
}
else{
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
final AlertDialog dialog = builder.create();
Button yesButton = (Button)dialogView.findViewById(R.id.dialog_notes_yes_button);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
dialog.dismiss();
}
});
dialog.show(); //new
}
}
}
You can make class that extend Dialog.
example:
public class CustomDialog extends Dialog {
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
lpWindow.dimAmount = 0.8f;
getWindow().setAttributes(lpWindow);
setContentView(R.layout.activity_custom_dialog);
editText = (EditText) findViewById(R.id.editText);
}
}
You can use this dialog..
mCustomDialog = new CustomDialog();
mCustomDialog.show();
You can make the layout as you wish.
======================================================================
You can use AlertDialog.Builder.setPositiveButton.
site : setPositiveButton
example...
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
builder.setPositiveButton("text", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
}
});
final AlertDialog dialog = builder.create();
dialog.show(); //new
I found the solution. Basically what was happening was that when the Keyboard appeared it would cause the listview to adjust the size recreating the whole listview with recycled/old versions of the list items from before the dialog appeared -effectively undoing any changes made to the ListView items by the dialog.
In your listview XML add this:
android:descendantFocusability="beforeDescendants"
In Mainfest.xml:
<activity android:name= ".yourActivity"
android:windowSoftInputMode="adjustPan"/>
Context
I'm working with popupwindows to allow a user to quickly rename a cardview in an activity.
I do this by using a ViewSwitcher to swap the TextView (original name) for an EditText(new name).
Problem
When the EditText and PopUpWindow to confirm are present an the user presses "RECENT APPS", you cannot for some reason get back into the app. ie. when you click it, it won't respond.
Diagnosis
I think it's an issue with Window Focus. I've tried EditText.clearFocus() from ET and dismissing all PopUps onPause, no luck.
Is there a way to use onFocusChangeListener to remove this issue?
Code (I've tried to remove as much superfluous items as possible)
TheHubActivity.java
public class TheHubActivity extends AppCompatActivity implements RecyclerViewAdapter.onCardClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// KEYBOARD
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//... Set up recycle view
rvContent = new ArrayList<>();
}
#Override
public void onCardLongClick(Flow longClickedFlow, int cardPosition, View cardViewClicked) {
showLongClickPopUpMenu(longClickedFlow,cardPosition, cardViewClicked);
}
private void showLongClickPopUpMenu(final Flow longClickedFlow, final int cardPosition, final View cardViewClicked) {
LayoutInflater layoutInflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup_window_longclick, null);
LinearLayout viewGroup = (LinearLayout) layout.findViewById(R.id.popup_longclick);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(layout, RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT);
popup.setFocusable(true);
// Getting a reference to Close button, and close the popup when clicked.
ImageView delete = (ImageView) layout.findViewById(R.id.popup_delete_item);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*.... Delete current Flow from internal file and UI */
popup.dismiss();
}
});
ImageView edit = (ImageView) layout.findViewById(R.id.popup_edit_item);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
renameFlow(cardPosition, cardViewClicked);
}
});
// Displaying the popup at the specified location, + offsets.
popup.showAsDropDown(cardViewClicked, cardViewClicked.getMeasuredWidth(),popupDisplayHeight, Gravity.TOP);
longClickPopup = popup;
}
private void renameFlow(final int cardPosition, final View cardViewClicked) {
final ViewSwitcher switcher = (ViewSwitcher) cardViewClicked.findViewById(R.id.rename_switcher);
final EditText rename = (EditText) switcher.findViewById(R.id.item_flow_rename);
rename.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (rename.hasFocus()) {
showEditPopupWindow(rename, cardViewClicked, switcher, cardPosition);
} else {
imm.hideSoftInputFromWindow(rename.getWindowToken(), 0);
}
}
});
switcher.showNext();
rename.requestFocus();
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY);
/* Forces keyboard */
}
private void showEditPopupWindow(final EditText newName, View cardViewClicked, final ViewSwitcher switcher, final int cardPosition) {
LayoutInflater layoutInflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup_window_editing, null);
LinearLayout viewGroup = (LinearLayout) layout.findViewById(R.id.popup_editing);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(layout, RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT);
popup.setFocusable(false); // So that user can edit text
// Getting a reference to Close button, and close the popup when clicked.
ImageView confirmEdit = (ImageView) layout.findViewById(R.id.popup_confirm_item_changes);
confirmEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* .. Changes name of cardview through edit text */
switcher.showNext();
popup.dismiss();
newName.clearFocus();
}
}
});
ImageView cancelEdit = (ImageView) layout.findViewById(R.id.popup_cancel_item_changes);
cancelEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switcher.showNext();
popup.dismiss();
}
});
popup.showAsDropDown(cardViewClicked, cardViewClicked.getMeasuredWidth(),popupDisplayHeight, Gravity.TOP);
editingPopup = popup;
}
#Override
protected void onPause() {
dismissPopups();
super.onPause();
}
private void dismissPopups() {
if (longClickPopup!=null && longClickPopup.isShowing()) {
longClickPopup.dismiss();
}
if (editingPopup!=null && editingPopup.isShowing()) {
editingPopup.dismiss();
}
}
}
For Visual People
I solved the issue... and it was surprisingly larger and completely unrelated to the Focus/PopUps (tunnel vision does that I guess).
In my Manifest I was using android:launchMode="singleTop" which was creating weird behaviour when TheHubActivity was sent to recent apps because this was my entrance activity. From the Developer Docs singleTop functions like so:
Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.
<activity
android:name=".TheHubActivity"
android:label="#string/app_name"
~~~~~~android:launchMode="singleTop"~~~~~~~~
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Hee guys,
So currently I'm using a PopupWindow to display an in app browser. However when pressing the back button it does nothing. I'm using the PopupWindow in another Fragment, then I use a statement to set the PopupWindow in my FragmentActivity and then when I press my back button it should check if the PopupWindow is set or not and dismiss it or not. However it doesn't even run through the onBackPressed.
PopupWindow in fragment:
--> is where I point out the line which makes sure the FragmentActivity gets the PopupWindow as well.
// Use webview for icons and website link.
public void inAppBrowser(String url){
mCursor.moveToFirst();
// Inflate View
LayoutInflater layoutInflater = (LayoutInflater) ((MainActivity) MainActivity.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View inflatedView = layoutInflater.inflate(R.layout.browser_window, null, false);
// Control View Childs.
LinearLayout header = (LinearLayout) inflatedView.findViewById(R.id.filter_header);
header.setBackgroundColor(Color.parseColor(color));
Button cancel = (Button) inflatedView.findViewById(R.id.cancel);
Button done = (Button) inflatedView.findViewById(R.id.done);
// Set PopupWindow position.
Display display = ((MainActivity) MainActivity.getContext()).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
// Control PopupWindow.
final PopupWindow popWindow = new PopupWindow(inflatedView, size.x, size.y, true);
popWindow.setAnimationStyle(android.R.anim.fade_in);
popWindow.setFocusable(true);
popWindow.setOutsideTouchable(true);
popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 150);
--> MainActivity.setPopupWindow(popWindow);
// Control WebView
WebView myWebView = (WebView) inflatedView.findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClientAdapter());
myWebView.clearCache(true);
myWebView.clearHistory();
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
MainActivity.setWebView(myWebView);
if (url != null) {
if (url.contains("http://") || url.contains("https://")) {
} else {
url = "http://" + url;
}
myWebView.loadUrl(url);
} else {
popWindow.dismiss();
MainActivity.setPopupWindow(null);
MainActivity.setWebView(null);
}
cancel.setVisibility(View.INVISIBLE);
done.setText("Close");
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popWindow.dismiss();
}
});
}
My onBackPressed code :
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
//check if popupwindow is open
Log.e(TAG, "Check if it runs through this section");
if (popWindow != null) {
if (myWebView != null && myWebView.canGoBack()) {
myWebView.goBack();
} else {
popWindow.dismiss();
popWindow = null;
myWebView = null;
}
}
}
Ignore the WebView for now. That might be a question in the future, but I want the PopupWindow to close first. Any help is appreciated.
Make your PopupWindow not focusable:
final PopupWindow popWindow = new PopupWindow(inflatedView, size.x, size.y, false);
Also remove this line which was redundant:
popWindow.setFocusable(true);
I think you should define a static method removePopupWindow(view v) in MainActivity,
and call it inside onBackPressed() like MainActivity.removePopupWindow(popWindow);
Hope It will help you.
Ok, so this question was asked a long time ago, but I think I have a better solution. What I've done is add an OnDismissListener to my popup. In this listener I've added the code I wanted to execute when the popup got dismissed. This way Android still get's to manage the opening and closing of the popup and I just added a single line to make it work.
This is the way to add one:
yourAwesomePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
// Your code on dismiss here
}
});
popup.showAtLocation(popupView, Gravity.CENTER,0,0);
popupshowing=true;// define this as a global
#Override
public void onBackPressed() {
if(popupshowing) {
popup.dismiss();
popupshowing=false;
}
else {
super.onBackPressed();
}
}
You can use this.
Dialog dialog = new Dialog(ActivityMain.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); dialog.setContentView(R.layout.mydialog);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
try {
if (mScannerView!=null) {
mScannerView.stopCamera();
}
} catch(Exception e){
e.printStackTrace();
}
}
});
To create a simple working PopupWindow, we need to do the following:
popup_example.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Test Pop-Up" />
</LinearLayout>
Java code
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup_example, null, false),100,100, true);
pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);
My requirement is that I need a
<TEXTVIEW android:layout_height="wrap_content" android:layout_width="fill_parent" />
and a
<BUTTON android:id="#+id/end_data_send_button" android:text="Cancel"/>
in my popup_example.xml. How can I handle these two components in my Java code?
How to make a simple Android popup window
This is a fuller example. It is a supplemental answer that deals with creating a popup window in general and not necessarily the specific details of the OP's problem. (The OP asks for a cancel button, but this is not necessary because the user can click anywhere on the screen to cancel it.) It will look like the following image.
Make a layout for the popup window
Add a layout file to res/layout that defines what the popup window will look like.
popup_window.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#62def8">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="30dp"
android:textSize="22sp"
android:text="This is a popup window."/>
</RelativeLayout>
Inflate and show the popup window
Here is the code for the main activity of our example. Whenever the button is clicked, the popup window is inflated and shown over the activity. Touching anywhere on the screen dismisses the popup window.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonShowPopupWindowClick(View view) {
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);
// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
// show the popup window
// which view you pass in doesn't matter, it is only used for the window tolken
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
}
}
That's it. You're finished.
Going on
Check out how gravity values effect PopupWindow.
You can also add a shadow.
Further study
These were also helpful in learning how to make a popup window:
PopupWindow documentation
How To Create Pop Up Window In Android (YouTube video)
Android Popup Window Example
Here, I am giving you a demo example. See this and customize it according to your need.
public class ShowPopUp extends Activity {
PopupWindow popUp;
boolean click = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
popUp = new PopupWindow(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout mainLayout = new LinearLayout(this);
TextView tv = new TextView(this);
Button but = new Button(this);
but.setText("Click Me");
but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (click) {
popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
popUp.update(50, 50, 300, 80);
click = false;
} else {
popUp.dismiss();
click = true;
}
}
});
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
tv.setText("Hi this is a sample text for popup window");
layout.addView(tv, params);
popUp.setContentView(layout);
// popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
mainLayout.addView(but, params);
setContentView(mainLayout);
}
}
Hope this will solve your issue.
are you done with the layout inflating? maybe you can try this!!
View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p
I construct my own class, and then call it from my activity, overriding small methods like showAtLocation. I've found its easier when I have 4 to 5 popups in my activity to do this.
public class ToggleValues implements OnClickListener{
private View pView;
private LayoutInflater inflater;
private PopupWindow pop;
private Button one, two, three, four, five, six, seven, eight, nine, blank;
private ImageButton eraser;
private int selected = 1;
private Animation appear;
public ToggleValues(int id, Context c, int screenHeight){
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pop = new PopupWindow(inflater.inflate(id, null, false), 265, (int)(screenHeight * 0.45), true);
pop.setBackgroundDrawable(c.getResources().getDrawable(R.drawable.alpha_0));
pView = pop.getContentView();
appear = AnimationUtils.loadAnimation(c, R.anim.appear);
one = (Button) pView.findViewById(R.id.one);
one.setOnClickListener(this);
two = (Button) pView.findViewById(R.id.two);
two.setOnClickListener(this);
three = (Button) pView.findViewById(R.id.three);
three.setOnClickListener(this);
four = (Button) pView.findViewById(R.id.four);
four.setOnClickListener(this);
five = (Button) pView.findViewById(R.id.five);
five.setOnClickListener(this);
six = (Button) pView.findViewById(R.id.six);
six.setOnClickListener(this);
seven = (Button) pView.findViewById(R.id.seven);
seven.setOnClickListener(this);
eight = (Button) pView.findViewById(R.id.eight);
eight.setOnClickListener(this);
nine = (Button) pView.findViewById(R.id.nine);
nine.setOnClickListener(this);
blank = (Button) pView.findViewById(R.id.blank_Selection);
blank.setOnClickListener(this);
eraser = (ImageButton) pView.findViewById(R.id.eraser);
eraser.setOnClickListener(this);
}
public void showAtLocation(View v) {
pop.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT, 40, 40);
pView.startAnimation(appear);
}
public void dismiss(){
pop.dismiss();
}
public boolean isShowing() {
if(pop.isShowing()){
return true;
}else{
return false;
}
}
public int getSelected(){
return selected;
}
public void onClick(View arg0) {
if(arg0 == one){
Sudo.setToggleNum(1);
}else if(arg0 == two){
Sudo.setToggleNum(2);
}else if(arg0 == three){
Sudo.setToggleNum(3);
}else if(arg0 == four){
Sudo.setToggleNum(4);
}else if(arg0 == five){
Sudo.setToggleNum(5);
}else if(arg0 == six){
Sudo.setToggleNum(6);
}else if(arg0 == seven){
Sudo.setToggleNum(7);
}else if(arg0 == eight){
Sudo.setToggleNum(8);
}else if(arg0 == nine){
Sudo.setToggleNum(9);
}else if(arg0 == blank){
Sudo.setToggleNum(0);
}else if(arg0 == eraser){
Sudo.setToggleNum(-1);
}
this.dismiss();
}
}
Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);
Similarly you can get the text view by adding a id to it.
LayoutInflater inflater = (LayoutInflater) SettingActivity.this.getSystemService(SettingActivity.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.gd_quick_action_slide_fontsize, null),LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, true);
pw.showAtLocation(SettingActivity.this.findViewById(R.id.setting_fontsize), Gravity.CENTER, 0, 0);
View v= pw.getContentView();
TextView tv=v.findViewById(R.id.....);
This an example from my code how to address a widget(button) in popupwindow
View v=LayoutInflater.from(getContext()).inflate(R.layout.popupwindow, null, false);
final PopupWindow pw = new PopupWindow(v,500,500, true);
final Button button = rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pw.showAtLocation(rootView.findViewById(R.id.constraintLayout), Gravity.CENTER, 0, 0);
}
});
final Button popup_btn=v.findViewById(R.id.popupbutton);
popup_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popup_btn.setBackgroundColor(Color.RED);
}
});
Hope this help you
Edit your style.xml with:
<style name="AppTheme" parent="Base.V21.Theme.AppCompat.Light.Dialog">
Base.V21.Theme.AppCompat.Light.Dialog provides a android poup-up theme