弹出菜单位于按钮的正下方和中心

时间:2018-06-25 21:03:05

标签: android popup

我当前正在制作一个包含一些数据的应用程序。我想在需要时编辑或删除它们。我创建了一个PopUp菜单,但问题是它出现在侧面,我希望它出现在单击按钮下方的中央。任何帮助将不胜感激。

这是我的片段活动

public class TemporaryKeyFragment extends Fragment implements PopupMenu.OnMenuItemClickListener{

private ListView lvItems;
private List<Product> lstProducts;

DatabaseReference database;

private int mDisplayDays;
private int mDisplayHours;
private int mDisplayMinutes;
private int mDisplaySeconds;

SwipeRefreshLayout swipeRefreshLayout;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.activity_my_keys, container, false);

    lvItems = (ListView) view.findViewById(R.id.lvItems);

    SharedPreferences prefs = getActivity().getSharedPreferences(LOCK_PREFS, MODE_PRIVATE);

    database = FirebaseDatabase.getInstance().getReference("Generated_Keys/"+prefs.getString("deviceId", null));

    database.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot usershot : dataSnapshot.getChildren()){
                lstProducts.add(new Product(usershot.child("Username").getValue().toString(),Long.parseLong(usershot.child("RemainingTime").getValue().toString())));
            }
            lvItems.setAdapter(new CountdownAdapter(getActivity().getApplicationContext(), lstProducts));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    lstProducts = new ArrayList<>();

    swipeRefreshLayout = view.findViewById(R.id.swipe);

    lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            PopupMenu popupMenu = new PopupMenu(getActivity(),view,Gravity.CENTER);
            popupMenu.getMenuInflater().inflate(R.menu.popupmenu, popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.edit:
                            Toast.makeText(getActivity().getApplicationContext(),"Edit Data ",Toast.LENGTH_LONG).show();
                            break;

                        case R.id.delete:
                            Toast.makeText(getActivity().getApplicationContext(),"Delete Data",Toast.LENGTH_LONG).show();
                            break;
                        default:
                            break;

                    }
                    return true;
                }
            });
            popupMenu.show();
            return true;
        }
    });



    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            database.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!dataSnapshot.exists()){
                        new AlertDialog.Builder(getActivity())
                                .setTitle("No Keys")
                                .setMessage("There are no current generated keys")
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        return;
                                    }})
                                .setNegativeButton(android.R.string.no, null).show();
                    }
                    for (DataSnapshot usershot : dataSnapshot.getChildren()){
                        lstProducts.add(new Product(usershot.child("Username").getValue().toString(),Long.parseLong(usershot.child("RemainingTime").getValue().toString())));
                    }
                    lvItems.setAdapter(new CountdownAdapter(getActivity().getApplicationContext(), lstProducts));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                }
            },2000);
            lstProducts.clear();
        }
    });
    return view;

}

/**
 * This method will be invoked when a menu item is clicked if the item
 * itself did not already handle the event.
 *
 * @param item the menu item that was clicked
 * @return {@code true} if the event was handled, {@code false}
 * otherwise
 */
@Override
public boolean onMenuItemClick(MenuItem item) {
    return false;
}

private class Product {
    String name;
    long expirationTime;

    public Product(String name, long expirationTime) {
        this.name = name;
        this.expirationTime = expirationTime;
    }
}


public class CountdownAdapter extends ArrayAdapter<Product> {
    private LayoutInflater lf;
    private List<ViewHolder> lstHolders;
    private Handler mHandler = new Handler();
    private Runnable updateRemainingTimeRunnable = new Runnable() {
        @Override
        public void run() {
            synchronized (lstHolders) {
                Time nowTime = new Time(Time.getCurrentTimezone());
                nowTime.setToNow();
                nowTime.normalize(true);
                long nowMillis = nowTime.toMillis(true);
                for (ViewHolder holder : lstHolders) {
                    holder.updateTimeRemaining();
                }
            }
        }
    };

    public CountdownAdapter(Context context, List<Product> objects) {
        super(context, 0, objects);
        lf = LayoutInflater.from(context);
        lstHolders = new ArrayList<>();
        startUpdateTimer();
    }

    private void startUpdateTimer() {
        Timer tmr = new Timer();
        tmr.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(updateRemainingTimeRunnable);
            }
        }, 1000, 1000);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = lf.inflate(R.layout.generated_list_item, parent, false);
            holder.tvProduct = (TextView) convertView.findViewById(R.id.tvProduct);
            holder.tvTimeRemaining = (TextView) convertView.findViewById(R.id.tvTimeRemaining);
            convertView.setTag(holder);
            synchronized (lstHolders) {
                lstHolders.add(holder);
            }
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.setData(getItem(position));

        return convertView;
    }
}

private class ViewHolder {
    TextView tvProduct;
    TextView tvTimeRemaining;
    Product mProduct;

    public void setData(Product item) {
        mProduct = item;
        tvProduct.setText(item.name);
        updateTimeRemaining();
    }

    public void updateTimeRemaining() {
        Time nowTime = new Time(Time.getCurrentTimezone());
        nowTime.setToNow();
        nowTime.normalize(true);
        long nowMillis = nowTime.toMillis(true);
        long timeDiff = mProduct.expirationTime - nowMillis;
        if (timeDiff > 0) {
            TemporaryKeyFragment.this.mDisplayDays = (int) (((timeDiff / 1000) / 86400));
            TemporaryKeyFragment.this.mDisplayHours = (int) (((timeDiff / 1000) - (TemporaryKeyFragment.this.mDisplayDays * 86400)) / 3600);
            TemporaryKeyFragment.this.mDisplayMinutes = (int) (((timeDiff / 1000) - ((TemporaryKeyFragment.this.mDisplayDays * 86400) + (TemporaryKeyFragment.this.mDisplayHours * 3600))) / 60);
            TemporaryKeyFragment.this.mDisplaySeconds = (int) ((timeDiff / 1000) % 60);
            tvTimeRemaining.setText(mDisplayDays + " days " + mDisplayHours + " hrs " + mDisplayMinutes+ " mins " + mDisplaySeconds + " sec");
        } else {
            tvTimeRemaining.setText("Expired!!");
        }
    }
}

我假设不需要布局,但是如果需要,请在下面添加注释。非常感谢

1 个答案:

答案 0 :(得分:0)

PopupMenu popupMenu = new PopupMenu(getActivity(),view,Gravity.BOTTOM); 

并通过按钮视图。