How to show Dialogue in fragment | Android - 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.

Related

How to get the value of clicked item of a custom listview inside the AlertDialog?

I have created a Custom listview inside the AlertDialog and set data by parsing a list. I need to get the clicked value of the individual object of that clicked row. But listView.setOnItemClickListener is not working. I have tried to solve this problem, but couldn't find a way. Please help me to solve this.
Thanks..
here is my code
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select A Customer");
//insert array to constructor
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.product_list_pop_up, null);
final CustomerPopupAdapter testAdapter = new CustomerPopupAdapter(getContext(), customers_data);
ListView listView = dialogLayout.findViewById(R.id.product_list_view);
TextView cancel_btn = dialogLayout.findViewById(R.id.cancel_btn);
TextView done_btn = dialogLayout.findViewById(R.id.done_btn);
listView.setAdapter(testAdapter);
builder.setView(dialogLayout);
final AlertDialog alert = builder.create();
alert.show();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("selected Item", "ListView ");
// customerName = testAdapter.getItem(position);
// customer_name.setText((CharSequence) testAdapter.getItem(position));
alert.dismiss();
}
});
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
done_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
here is my adapter
public class CustomerPopupAdapter extends ArrayAdapter<Customer> {
private List<Customer> list;
public CustomerPopupAdapter(Context context, List<Customer> test) {
super(context, R.layout.discount_popup_row, test);
this.list = test;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final Customer customer = list.get(position);
View customRow = inflater.inflate(R.layout.customer_popup_row, parent, false);
TextView customer_name = customRow.findViewById(R.id.customer_name);
TextView customer_id = customRow.findViewById(R.id.customer_id);
customer_id.setText(customer.getId());
customer_name.setText(customer.getName());
return customRow;
}
}
here is the custom_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/match_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/activity_margin_10dp"
android:weightSum="3">
<TextView
android:id="#+id/customer_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Username"
android:inputType="text"
android:layout_weight="1"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
<TextView
android:id="#+id/customer_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="id"
android:inputType="text"
android:layout_weight="2"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
</LinearLayout>
<View
android:id="#+id/bottom_border"
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_marginTop="#dimen/activity_margin_5dp"
android:background="#color/colorGrey" />
</LinearLayout>
Use your customers_data list to get the clicked value.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("selected Item", customers_data.get(position));
alert.dismiss();
}
});
You i am not sure why your code is not working if you can post the project that would be very really helpful or at least the whole activity ,so this is how you can easily display list in alert box .
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");
// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // horse
case 1: // cow
case 2: // camel
case 3: // sheep
case 4: // goat
}
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Check the full reference https://stackoverflow.com/a/43532478/9638167
Don't use ListView, read this: Should we use RecyclerView to replace ListView? and other materials on google, RecyclerView is the way to go
I think what you need is:
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//element selected is yourList.get(position);
}
});
Actually, this is an answer for this question. I have added android: inputType="text" to the code. It was the problem. I removed it and then it works perfectly.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/match_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/activity_margin_10dp"
android:weightSum="3">
<TextView
android:id="#+id/customer_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Username"
android:layout_weight="1"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
<TextView
android:id="#+id/customer_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="id"
android:layout_weight="2"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
</LinearLayout>
<View
android:id="#+id/bottom_border"
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_marginTop="#dimen/activity_margin_5dp"
android:background="#color/colorGrey" />
</LinearLayout>
The answer was given by the "I_A_Mok", All the credits should goes to him.
Please remove the android:inputType="text" from your xml. this will solve your problem. Thanks.

Apply style to spinner

I want to work with the spinner item.
I want the drop down to have the same width and height than the button.
How can I do this?
Finally i solved it using a listview into a alertdialog like this:
public void seleccionaTemporada(View view) {
AlertDialog.Builder selector = new AlertDialog.Builder(SeleccionaTemporadaActivity.this);
selector.setTitle("Temporadas");
selector.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
selector.setAdapter(temporadas, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), DashBoardActivity.class);
intent.putExtra("temporada", temporadas.getItem(which));
startActivity(intent);
}
});
selector.show();
}
<Button
android:id="#+id/btn_selecciona_temporada"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="70dp"
android:drawableStart="#mipmap/ic_balon"
android:onClick="seleccionaTemporada"
android:text="#string/seleccionarTemporada"
android:textSize="25sp" />
For my needs it is the best solution i think. Sorry for my bad explanation before.
You can use Popup Window. And create your own Spinner Popup.
Example Code below
LayoutInflater inflater = (LayoutInflater)parentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.pop_up_window, null);
RelativeLayout layout1 = holder.relativeLayout_multiChoiceDropDown;
pw = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
pw.setBackgroundDrawable(new BitmapDrawable());
pw.setTouchable(true);
pw.setOutsideTouchable(true);
pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
pw.setTouchInterceptor(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
{
pw.dismiss();
return true;
}
return false;
}
});
pw.setContentView(layout);
pw.showAsDropDown(layout1, -5, 0);
final ListView list = (ListView) layout.findViewById(R.id.dropDownList);
Adapter_DropDown adapter = new Adapter_DropDown(parentActivity, items);
list.setAdapter(adapter);
pop_up_window.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/PopUpView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/qatool_basic_info_dropdown"
android:orientation="vertical">
<ListView
android:id="#+id/dropDownList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="0.5dp">
</ListView>
</LinearLayout>

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);
}
}

setOnChildClickListener of ExpandableListView inside a Custom Alter dialog does not work

I have created a custom Alert Dialog with a ExpandableListView inside it. The ExpandableListView childs are Checkboxes.
I am trying to set the event listener whenever the user clicks on one of the checkboxes but it does not work. I can select and unselect the checkboxes in the custom alert dialog but the event handler does not work. Can anyone help me?
Code to create the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select the route or segments");
LinearLayout layout = (LinearLayout) findViewById(R.id.custom_alert_dialog);
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.custom_alert_dialog_routes, null);
ExpandableListView listView = (ExpandableListView) dialoglayout.findViewById(R.id.routesListView);
ExpandableListAdapter listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
listView.setAdapter(listAdapter);
listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), "Clicked the checkbox", Toast.LENGTH_LONG).show();
Log.d("Click", "I have clicked a checkbox.");
return false;
}
});
builder.setView(dialoglayout);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New CheckBox"
android:id="#+id/expandedListItem"
android:textColor="#000000"
android:focusable="false"
android:layout_marginLeft="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"/>
</LinearLayout>
I have tried with the android:focusable and without it and it did not work.
Try using setOnItemClickListener instead of setOnChildClickListener.

Android MenuItem Custom Layout

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);

Categories

Resources