Android MenuItem Custom Layout - android

I have a PopupMenu that appears when I click on an action button in a actionbar.
I would like the MenuItem, in my PopupMenu, with a custom layout like this:
layout/menu_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/menuItemLayout"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageViewMenuItem"
android:layout_width="20dip"
android:layout_height="20dip"
android:src="#drawable/abc_list_focused_holo" />
<TextView
android:id="#+id/textViewMenuItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextViewMenuItem" />
</LinearLayout>
This is the xml of PopUpMenu:
menu/pop_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="apparound.actiobarpopupstylefacebook.Main" >
<item
android:id="#+id/popupItem"
android:showAsAction="ifRoom"/>
</menu>
In my activity code is following:
public void showPopup(int idR){
View menuItemView = findViewById(idR);
PopupMenu popup = new PopupMenu(this, menuItemView);
MenuInflater inflate = popup.getMenuInflater();
inflate.inflate(R.menu.pop_menu, popup.getMenu());
MenuItem menuItem= popup.getMenu().findItem(R.id.popupItem);
menuItem.setActionView(R.layout.menu_item_layout);
popup.show();
}
But when appear popupmenu, item is empty.
I was wrong to use setActionview() method?
Thanks.

For custom layouts you can't use a menu, one alternate option is a PopupWindow
PopupWindow popupwindow_obj = popupDisplay();
popupwindow_obj.showAsDropDown(clickbtn, -40, 18); // where u want show on view click event popupwindow.showAsDropDown(view, x, y);
public PopupWindow popupDisplay()
{
final PopupWindow popupWindow = new PopupWindow(this);
// inflate your layout or dynamically add view
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.mylayout, null);
Button item = (Button) view.findViewById(R.id.button1);
popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(view);
return popupWindow;
}
Create this XML file in the res/layout folder named my layout.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Window test" />
</LinearLayout>

Final PopupWindow popupWindow = new PopupWindow(); // inflate your layout or dynamically add view
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.alert_reply_chat,null); popupWindow.setFocusable(true); popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(180); popupWindow.setBackgroundDrawable(null); popupWindow.setClippingEnabled(false); popupWindow.setTouchable(true); popupWindow.setContentView(view); return popupWindow;
//above is working code i checked it

By default the layout of a PopupMenu (and it's items) cannot be customized. In the solution below I have created a PopupMenu with a horizontal layout. In this case I used TextView as clickable items, but you can easily replace them by Buttons. You can customize the menu items whatever you want.
1 - The Custom PopupMenu class:
public class PopupMenuCustomLayout {
private PopupMenuCustomOnClickListener onClickListener;
private Context context;
private PopupWindow popupWindow;
private int rLayoutId;
private View popupView;
public PopupMenuCustomLayout(Context context, int rLayoutId, PopupMenuCustomOnClickListener onClickListener) {
this.context = context;
this.onClickListener = onClickListener;
this.rLayoutId = rLayoutId;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
popupView = inflater.inflate(rLayoutId, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true;
popupWindow = new PopupWindow(popupView, width, height, focusable);
popupWindow.setElevation(10);
LinearLayout linearLayout = (LinearLayout) popupView;
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
v.setOnClickListener( v1 -> { onClickListener.onClick( v1.getId()); popupWindow.dismiss(); });
}
}
public void setAnimationStyle( int animationStyle) {
popupWindow.setAnimationStyle(animationStyle);
}
public void show() {
popupWindow.showAtLocation( popupView, Gravity.CENTER, 0, 0);
}
public void show( View anchorView, int gravity, int offsetX, int offsetY) {
popupWindow.showAsDropDown( anchorView, 0, -2 * (anchorView.getHeight()));
}
public interface PopupMenuCustomOnClickListener {
public void onClick(int menuItemId);
}
}
2 - Your custom layout, e.g. linearlayout with horizontal layout. In this case I use a simple LinearLayout with TextView items. You can use Buttons, etc.
<?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="wrap_content"
android:background="#color/white"
android:orientation="horizontal">
<TextView
android:id="#+id/popup_menu_custom_item_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="A"
android:textAppearance="?android:textAppearanceMedium" />
<TextView
android:id="#+id/popup_menu_custom_item_b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="B"
android:textAppearance="?android:textAppearanceMedium" />
// ...
</LinearLayout>
3 - Using the Custom PopupMenu like the normal PopupMenu.
PopupMenuCustomLayout popupMenu = new PopupMenuCustomLayout(
MainActivity.mainActivity, R.layout.popup_menu_custom_layout,
new PopupMenuCustomLayout.PopupMenuCustomOnClickListener() {
#Override
public void onClick(int itemId) {
// log statement: "Clicked on: " + itemId
switch (itemId) {
case R.id.popup_menu_custom_item_a:
// log statement: "Item A was clicked!"
break;
}
}
});
// Method 1: popupMenu.show();
// Method 2: via an anchor view:
popupMenu.show( anchorView, Gravity.CENTER, 0, 0);

Related

Android popup window not filling screen size?

I am trying to make a simple pop up window. But every time I make one, it ends up being super small...and not the length I want it to be. This is how the pop up looks:
Here is my layout for the pop up:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:padding="10px"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Transfering data"
android:textColor="#color/white"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Status"
android:textColor="#color/white"/>
<TextView android:id="#+id/server_status_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Awaiting answer..."
android:paddingLeft="10sp"
android:textColor="#color/white"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:gravity="center_horizontal|bottom">
<Button android:id="#+id/end_data_send_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:drawablePadding="3sp"
android:layout_centerHorizontal="true"
android:text="Cancel" />
</LinearLayout>
</LinearLayout>
Here is my java code:
private PopupWindow pw;
private void bindActivity() {
fabButton = (ImageButton) findViewById(R.id.activity_profileView_FAB);
fabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
}
});
}
private void initiatePopupWindow() {
try {
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) ProfileView.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
// create a 300px width and 470px height PopupWindow
pw = new PopupWindow(layout, 300, 470, true);
// display the popup in the center
pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);
Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
cancelButton.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
public void onClick(View v) {
pw.dismiss();
}
};
Cant figure out why its not working...
How would I get the size I want?
Here you can't use layout which is in your popup window xml. You have to use any View from main layout. Right now I am using FloatingButton as a View to showAtLocation.
fabButton = (ImageButton) findViewById(R.id.activity_profileView_FAB);
fabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
initiatePopupWindow(v);
}
});
private void initiatePopupWindow(View v) {
try {
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) ProfileView.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
// create a 300px width and 470px height PopupWindow
pw = new PopupWindow(layout, 300, 470, true);
// display the popup in the center
pw.showAtLocation(v, Gravity.CENTER, 0, 0);
TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);
Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
cancelButton.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
Just change
pw = new PopupWindow(layout, 300, 470, true);
to like this
pw = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, true);
and if you need margins on any side do it in popup xml file. Also in xml use android:layout_height="wrap_content". Advantage of this is,- it will look same (if you put margin) in any device screen.

Unable to click on the items of PopupWindow

I am implementing the following screen:
Here you can see i have a popup containing different icons like Gallery,Photos etc.
The layout for popup is :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/while_color"
android:orientation="vertical"
android:padding="#dimen/padding10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/gallery"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/padding10"
android:drawableTop="#drawable/gallery"
android:gravity="center"
android:text="Gallery" />
<TextView
android:id="#+id/photos"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/padding10"
android:drawableTop="#drawable/photos"
android:gravity="center"
android:text="Photos" />
<TextView
android:id="#+id/videos"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/padding10"
android:drawableTop="#drawable/videos"
android:gravity="center"
android:text="Video" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin10"
android:orientation="horizontal">
<TextView
android:id="#+id/audio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/padding10"
android:drawableTop="#drawable/audio"
android:gravity="center"
android:text="Audio" />
<TextView
android:id="#+id/location"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/padding10"
android:drawableTop="#drawable/location"
android:gravity="center"
android:text="Location" />
<TextView
android:id="#+id/contacts"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/padding10"
android:drawableTop="#drawable/contacts"
android:gravity="center"
android:text="Contacts" />
</LinearLayout>
</LinearLayout>
I am using the following code to attach the popup under toolbar:
//inflate the popupwindow_attachment.xml
LinearLayout viewGroup = (LinearLayout) SingleChatActivity.this.findViewById(R.id.popup_element);
LayoutInflater inflater = (LayoutInflater) SingleChatActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popupwindow_attachment, viewGroup);
PopupWindow popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//Close the popup when touch outside
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_viewContacts:
return true;
case R.id.action_media:
return true;
case R.id.action_search:
return true;
case R.id.action_block:
return true;
case R.id.action_email_chat:
return true;
case R.id.action_clear_chat:
return true;
case R.id.action_attach:
initializePopUpWindow();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initializePopUpWindow() {
//Placing the popup window below the toolbar
popupWindow.showAsDropDown(toolbar, 0, 0);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.popupwindow_attachment, null);
TextView gallery = (TextView) v.findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Gallery Clicked", Toast.LENGTH_SHORT).show();
}
});
}
Here i am trying to toast the message on clicking the Gallery icon ,but it is not working for me.Please help to access the icons of a popup window.
You are inflating your popup view again in initializePopUpWindow() method and this view you are not using that's why you not getting click.
Declare your click event code where you wrote popup window code.
LinearLayout viewGroup = (LinearLayout) SingleChatActivity.this.findViewById(R.id.popup_element);
LayoutInflater inflater = (LayoutInflater) SingleChatActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popupwindow_attachment, viewGroup);
PopupWindow popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//Close the popup when touch outside
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
TextView gallery = (TextView)layout.findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Gallery Clicked", Toast.LENGTH_SHORT).show();
}
});
You can get popup window icon using popup view.
LinearLayout viewGroup = (LinearLayout) SingleChatActivity.this.findViewById(R.id.popup_element);
LayoutInflater inflater = (LayoutInflater) SingleChatActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popupwindow_attachment, viewGroup);
PopupWindow popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//you can access popup icon and click
TextView gallery = (TextView)layout.findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
//or
layout.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
//or
gallery.setOnClickListener(this);
//Close the popup when touch outside
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

Dimmed Background of PopupWindow excludes Toolbars / Action Bars

I use the following codes to create a PopupWindow with dim background by clicking a menu item in Toolbar:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.btn_1:
Log.i(TAG, "Clicked Button 1");
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup_window, null);
final PopupWindow popupWindow = new PopupWindow(popupView, Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.MATCH_PARENT);
Button btnDismiss = (Button)popupView.findViewById(R.id.btn_dismiss);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
However, I want to the dim background to exclude the action bars / toolbars. How can I achieve it?
The layout of the PopupView is as follow:
<?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">
<RelativeLayout
android:id="#+id/bac_dim_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C0000000"
android:visibility="visible" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="1dp"
android:background="#android:color/darker_gray">
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="20dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="It's a PopupWindow" />
<Button
android:id="#+id/btn_dismiss"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Dismiss" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
if you want popup window to display with dim background except ToolBar/ActionBar
here i tried setting position of popup window. fetch statusbar & navigation bar height & set Y position to the popup
int actionBarHeight = 0;
View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
actionBarHeight = getNavigationBarHeight(getActivity(), Configuration.ORIENTATION_PORTRAIT);
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
actionBarHeight = actionBarHeight + getResources().getDimensionPixelSize(resourceId);
}
Button btnDismiss = (Button) popupView.findViewById(R.id.btn_dismiss);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(popupView, 0, actionBarHeight);
Another way to display popup as you said in comment.Below mentioned you can try
Take one hidden control(TextView) in layout which will be aligned to top. Take the location of the TextView & assigned Y position to popup window
public class MyPopupTest extends Fragment{
public static final String TAG = "MyPopupTest";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_screen_slider, container, false);
}
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.btnSelect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopup(view);
}
});
}
public void showPopup(View view) {
View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
Button btnDismiss = (Button) popupView.findViewById(R.id.btn_dismiss);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
int[] locationOfHiddenTextView = new int[2];
view.findViewById(R.id.hiddenTopTextView).getLocationOnScreen(locationOfHiddenTextView);
//Give Position as a start point for popup
popupWindow.showAsDropDown(popupView, 0, locationOfHiddenTextView[1]);
}
}
XML File of the fragment which is goint to display
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffc699">
<TextView
android:id="#+id/hiddenTopTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone" />
<Button
android:id="#+id/btnSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup" />
</RelativeLayout>
I have a solution, but I only test with DialogFragment, not sure it works with dialog or not. I will post it anyway:
1. create your own class which extends DialogFragment.
2. create xml file with your designed dim color:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80000000" // your designed dim color
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/goto_dialog_title"
android:textColor="#android:color/white"
android:textSize="#dimen/km_25sp"/>
3. Override funcions in your DialogFragment:
private class MyDialog extends DialogFragment{
//override your onCreateView to show your xml here
//override onCreate to show dialog without border and without dim background
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, 0);
}
// override to show dim background and avoid dimming actionbar
#Override
public void onResume() {
super.onResume();
int statusBarAndActionBarHeight = 200; //u should calculate yourself
Window window = getDialog().getWindow();
// set size to your dialog --> fullscreen size to show dim bg all screen except action bar and status bar
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
window.setLayout(displaymetrics.widthPixels, displaymetrics.heightPixels - statusBarAndActionBarHeight);
//margin top to avoid dim background above actionbar and status bar
WindowManager.LayoutParams p = window.getAttributes();
p.y = statusBarAndActionBarHeight;
getDialog().getWindow().setGravity(Gravity.TOP);
getDialog().getWindow().setAttributes(p);
}
}

How to show Dialogue in fragment | Android

Using fragment in my activity , i want to show a dialogue On ItemLongClickListener of viewlist. I have tried a few codes but failed. Is there anyway to do it?
code
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View v,int index, long arg3) {
Toast.makeText(getActivity(),"thul thuk!",Toast.LENGTH_SHORT).show();
//show-dialogue here
return false;
}
});
Try this..
custom_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF" />
</LinearLayout>
Java
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View v,int index, long arg3) {
Toast.makeText(getActivity(),"thul thuk!",Toast.LENGTH_SHORT).show();
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
dialog.show();
return false;
}
});
EDIT
You can use Context Menu
Try this:
public void showPopup(View anchorView) {
View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button proceed = (Button)popupView.findViewById(R.id.button1);
Button cancel = (Button)popupView.findViewById(R.id.button2);
cb = (CheckBox)popupView.findViewById(R.id.checkBox1);
proceed.setOnClickListener(onProceed);
cancel.setOnClickListener(onCan);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable());
int location[] = new int[2];
anchorView.getLocationOnScreen(location);
popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY,
location[0], location[1] + anchorView.getHeight());
}
The above will result in a popup, just beneath the view clicked.
popup_layout is the XML layout file which will be inflated.

How to get the position of an Item from a PopupMenu in a custom ListView

Here's the problem: I've got a custom ArrayAdapter (overriden getView). Each item has got
2 ImageView
2 EditText
One of those ImageView is clickable and enables a PopupMenu, so I've got a little PopupMenu for each item of the list. Now, for that menu I need some parameters from the item to wich is anchored. So, how to pass informations (like position) to the method called from the PopupMenu voice? Attached the xml files.
item_list.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="wrap_content"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:maxHeight="60dp"
android:text="Title"
android:textSize="16sp" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:contentDescription="TODO"
android:onClick="showMenu"
android:src="#drawable/abc_ic_menu_moreoverflow_normal_holo_light" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentLeft="true"
android:layout_below="#+id/firstLine"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Author"
android:textSize="12sp" />
</RelativeLayout>
</LinearLayout>
menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/preview"
android:onClick="preview"
android:title="#string/preview"/>
<item
android:id="#+id/download"
android:onClick="download"
android:title="#string/download"/>
</menu>
CustomArrayAdapter.java
public class CustomArrayAdapter extends ArrayAdapter<Custom>{
private final Context context;
private final List<Custom> values;
private final int resource;
private final ImageCache imgCache = new ImageCache();
public CustomArrayAdapter(Context context, int resource, List<Custom> values) {
super(context, resource, values);
this.context = context;
this.values = values;
this.resource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
Custom Custom = values.get(position);
if (convertView == null) {
vh = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resource, parent, false);
vh.title = (TextView) convertView.findViewById(R.id.firstLine);
vh.author = (TextView) convertView.findViewById(R.id.secondLine);
vh.albumImage = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(vh);
}
else {
vh = (ViewHolder)convertView.getTag();
}
vh.requestedCustom = Custom;
vh.title.setText(Custom.getTitle());
vh.author.setText(Custom.getAuthor());
String imgUrl = Custom.getImgUrl();
if (imgUrl != null) {
imgCache.getImage(Custom, vh);
}
else {
vh.albumImage.setImageResource(R.drawable.no_album);
}
return convertView;
}
// This is a ViewHolder that helps in the view recycling
public static class ViewHolder {
public Custom requestedCustom;
public TextView title;
public TextView author;
public ImageView albumImage;
}
}
"preview" and "download" methods need parameters from the associated list item and I don't know how to get them. Thanks again.
EDIT 1
It seems that a Contextual Menu should be used instead (right?) but I would like to anchor it to each item as a sort of popup menu that appears. So how can I achieve this?
For those who don't understand what I want (due to my worst english): Google Play app, popup menu that let you choose between "Install" or "Add to whishlist".
You can create your listener class like this:
class myClickListener implements OnClickListener, OnMenuItemClickListener {
long id;
public myClickListener(long id) {
this.id = id;
}
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(appContext, v);
popup.setOnMenuItemClickListener(this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_item, popup.getMenu());
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem arg0) {
Toast.makeText(appContext, "ID of selected row : " + id , Toast.LENGTH_SHORT).show();
return false;
}
}
and add this listener to your imageview at your override getView method of adapter class:
imageView.setOnClickListener(new myClickListener(getItemId(position)));
Simply we need to set buttons tag as its position, and onClick on the PopupButton you need to get the view:
button.setTag(position); //may be you can call this on getview method of list view
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int position = (Integer) v.getTag(); // you will get the position
}
});
or use Interface in your fragment implements View.OnClickListener
private void showPopupMenu(View view) {
final int position = (Integer) view.getTag();
PopupMenu popup = new PopupMenu(getActivity(), view);
// Inflate our menu resource into the PopupMenu's Menu
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
// Set a listener so we are notified if a menu item is clicked
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_remove:
System.out.println(position);
return true;
}
return false;
}
});
// Finally show the PopupMenu
popup.show();
}
There is no way to achieve what you want with a onClick declared by XML. The easiest way to solve it with your actual implementation is to :
add a real click listener to your ImageView after inflating it. Inside your adapter.
the listener should be a custom class implementing the OnClickListener interface
you should also give your listener an additional data member : the position (row) that contains the ImageView.
when the listener is activated, it will have to invoke a callback on the activity that will display the Dialog, the listener will then pass the position.
Here's how I did it:
Instead of storing a ViewHolder in the tags of convertView in CustomArrayAdapter's getView(int position, View convertView, ViewGroup parent) method, I stored the Custom object itself. I didn't even use a holder.
convertView.setTag(getItem(position));
(if you really need to store the ViewHolder, you can use setTag(int key, Object tag)
to store multiple tags)
When showMenu(View view) is called by the ImageView, I use view.getParent() to get the parent LinearLayout of the currently selected view, which has my Custom object in its tag.
View parent = (View) view.getParent();
Outside showMenu() I have defined a public property to store the currently selected item like this:
public static Custom mSelectedItem;
Inside showMenu() I set mSelectedItem to getTag() of the parent LinearLayout from step 2.
mSelectedItem = (Custom) parent.getTag();
Finally, in the onMenuItemClick(MenuItem menuItem) override method I use mSelectedItem to determine the currently selected item.
Custom custom = mSelectedItem;

Categories

Resources