Android opencontextmenu dialog app

Содержание
  1. Диалоговые окна в Android. Часть 1
  2. Android opening context menu after button click
  3. 4 Answers 4
  4. Dialog
  5. Class Overview
  6. Developer Guides
  7. Summary
  8. Public Constructors
  9. public Dialog (Context context)
  10. public Dialog (Context context, int theme)
  11. Protected Constructors
  12. protected Dialog (Context context, boolean cancelable, DialogInterface.OnCancelListener cancelListener)
  13. Public Methods
  14. public void addContentView (View view, ViewGroup.LayoutParams params)
  15. public void cancel ()
  16. public void closeOptionsMenu ()
  17. public void dismiss ()
  18. public boolean dispatchGenericMotionEvent (MotionEvent ev)
  19. public boolean dispatchKeyEvent (KeyEvent event)
  20. public boolean dispatchKeyShortcutEvent (KeyEvent event)
  21. public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)
  22. public boolean dispatchTouchEvent (MotionEvent ev)
  23. public boolean dispatchTrackballEvent (MotionEvent ev)
  24. public View findViewById (int id)
  25. public ActionBar getActionBar ()
  26. public final Context getContext ()
  27. public View getCurrentFocus ()
  28. public LayoutInflater getLayoutInflater ()
  29. public final Activity getOwnerActivity ()
  30. public final int getVolumeControlStream ()
  31. public Window getWindow ()
  32. public void hide ()
  33. public void invalidateOptionsMenu ()
  34. public boolean isShowing ()
  35. public void onActionModeFinished (ActionMode mode)
  36. public void onActionModeStarted (ActionMode mode)
  37. public void onAttachedToWindow ()
  38. public void onBackPressed ()
  39. public void onContentChanged ()
  40. public boolean onContextItemSelected (MenuItem item)
  41. public void onContextMenuClosed (Menu menu)
  42. public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
  43. public boolean onCreateOptionsMenu (Menu menu)
  44. public boolean onCreatePanelMenu (int featureId, Menu menu)
  45. public View onCreatePanelView (int featureId)
  46. public void onDetachedFromWindow ()
  47. public boolean onGenericMotionEvent (MotionEvent event)

Диалоговые окна в Android. Часть 1

Dialog

Dialog — это класс, принадлежащий Android SDK и помогающий нам, простым смертным программистам, работать с диалоговыми окнами в Android. Класс Dialog имеет 4 подкласса:

  • AlertDialog: это диалоговое окно для различных сообщений приложения, например «Вы хотите купить мое приложение?» или что то в этом роде. AlertDialog поддерживает три кнопки — утвердительную (OK), отрицательную (Cancel) и нейтральную (Later).
  • ProgressDialog: это диалоговое окно для отображения выполнения различных процессов, загрузки, например.
  • DatePickerDialog: диалоговое окно предлагает пользователю выбрать дату.
  • TimePickerDialog: диалоговое окно предлагает пользователю выбрать время

На первом из этого списка, AlertDialog мы и остановимся подробнее.

AlertDialog

Чтобы создать диалоговое окно AlertDialog нам в помощь потребуется экземпляр класса Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Теперь, когда у нас есть builder, мы можем «строить» свое собственное диалоговое окно. В параметры диалогового окна Вы можете написать множество различных параметров, но основными являются эти:

  • setTitle(int resID) — задает заголовок диалогового окна, принимает в качестве аргументов ссылку на ресурс или строку.
  • setMessage(int resID) — задает сообщение в диалоговом окне, также принимает ссылку на ресурс или строку.
  • setPositiveButton(int textID, DialogInterface.OnClickListener listener) — устанавливает на Вашем диалоговом окне утвердительную кнопку с текстом ресурса textID и слушателем listener. Методы setNegativeButton и setNeutralButton идентичны, с разницей в назначении кнопок.

Пример создания AlertDialog:

В этом примере я использовал setCancelable(true) — это разрешает пользователю закрывать диалоговое окно с помощью хардварной кнопки Back. Еще я создал слушателя для утвердительной кнопки и использовал метод create(). Метод create() возвращает готовое диалоговое окно с вашими параметрами как экземпляр класса AlertDialog.
Вот мы и создали диалоговое окно! Следующая задача — показать его пользователю. Вот тут есть несколько вариантов:

  • showDialog(AlertDialog dialog) — самый простой способ показать диалоговое окно, но начиная с версии 3.0 разработчики Android не рекомендуют пользоваться этим методом, и в результате вы получите предупреждение, которое можно обойти только @SurpressWarning, что есть не совсем хорошо.
  • AlertDialog dialog.show() — альтернативный способ показать окно, для этого в экземпляре dialog должен лежать результат метода Builder.create().

Второй метод нам подходит больше, но писать в основной активности кучу различных Buider и AlertDialog портит читабельность кода. Поэтому целесообразней вынести создание и обработку диалоговых окон в новый класс, например:

Единственная заметка по поводу этого кода будет про использования метода setView(View view) в диалоге IDD_SETTINGS. У AlertDialog как и у всех остальных диалоговых окон есть одна приятная особенность — им можно задавать собственные Layout, что позволяет полностью видоизменять диалоговые окна и их содержимое. Здесь есть один подводный камень: обработку элементов этого Layout вы должны будете производить именно в той Activity, где вызываете это диалоговое окно. Например я показываю диалоговое окно IDD_SETTINGS в MainActivity с Layout по имени settings:

Соответственно я загружаю это окно в MainActivity:

Метод initSettings класса MainActivity в данном случае будет выглядеть так:

Ну а дальше обрабатываете свои объекты как вам угодно.

Читайте также:  Андроид студио долго запускается
Небольшой итог

1) Для большинства целей диалоговых окон подходит AlertDialog
2) AlertDialog может принимать вид layout с любыми объектами
3) Гораздо лучше использовать для диалоговых окон отдельный класс и пользоваться AlertDialog.show()
4) Обработка объектов кастомного layout производится в активности, вызвавшей диалог

В следующей части этой статьи пойдет речь о DialogFragment, который был включен в Android SDK начиная с 3.0 Honeycomb. Надеюсь эта статья поможет новичкам и не очень в своих квестах по завоеванию Google Play.

Источник

Android opening context menu after button click

I want to open context menu when I click a button, but also I have to know which list item is focused when I click the button. Do you know how to do that? What code should be in onclick method?

4 Answers 4

I was looking for the same, and found that instead of context menu, you should use Dialogs

If you really want to do it for whatever reason. (in my case, out of laziness)

During onCreate of your activity or somewhere before your user can touch the button, do registerForContextMenu on that button. Then in the actual button onClick handler, call openContextMenu(View) .

For example, I have a button declared in xml like

and in onHelp function

this works because the View v is the same as the view registered for context menu.

First thing, you should register the view by calling registerForContextMenu(View view). Second, override the onCreateContextMenu() to add the menus and lastly, override the onContextItemSelected() to put logic on each menu.

First of all, you should know why you should use ContextMenu . The functionality of ContextMenu of a View is similar to the right-click menu on a PC, which means the «available operations» on some item.

According to your description, I think what you actually need is a customized Dialog with a list, which is displayed when clicking the Button and is also able to get the focused item of your ListView . Then you can save the registration of ContextMenu for some View that really needs the menu:)

Источник

Dialog

java.lang.Object
android.app.Dialog
Known Direct Subclasses
AlertDialog A subclass of Dialog that can display one, two or three buttons.
CharacterPickerDialog Dialog for choosing accented characters related to a base character.
Presentation Base class for presentations.

A dialog showing a progress indicator and an optional text message or view.

TimePickerDialog A dialog that prompts the user for the time of day using a TimePicker .

Class Overview

Base class for Dialogs.

Note: Activities provide a facility to manage the creation, saving and restoring of dialogs. See onCreateDialog(int) , onPrepareDialog(int, Dialog) , showDialog(int) , and dismissDialog(int) . If these methods are used, getOwnerActivity() will return the Activity that managed this dialog.

Often you will want to have a Dialog display on top of the current input method, because there is no reason for it to accept text. You can do this by setting the WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM window flag (assuming your Dialog takes input focus, as it the default) with the following code:

Developer Guides

For more information about creating dialogs, read the Dialogs developer guide.

Summary

int BUTTON1 This constant was deprecated in API level 3. Use BUTTON_POSITIVE
int BUTTON2 This constant was deprecated in API level 3. Use BUTTON_NEGATIVE
int BUTTON3 This constant was deprecated in API level 3. Use BUTTON_NEUTRAL
int BUTTON_NEGATIVE The identifier for the negative button.
int BUTTON_NEUTRAL The identifier for the neutral button.
int BUTTON_POSITIVE The identifier for the positive button.
Protected Constructors
Public Methods

Public Constructors

public Dialog (Context context)

Create a Dialog window that uses the default dialog frame style.

Parameters
context The Context the Dialog is to run it. In particular, it uses the window manager and theme in this context to present its UI.

public Dialog (Context context, int theme)

Create a Dialog window that uses a custom dialog style.

Parameters
context The Context in which the Dialog should run. In particular, it uses the window manager and theme from this context to present its UI.
theme A style resource describing the theme to use for the window. See Style and Theme Resources for more information about defining and using styles. This theme is applied on top of the current theme in context . If 0, the default dialog theme will be used.

Protected Constructors

protected Dialog (Context context, boolean cancelable, DialogInterface.OnCancelListener cancelListener)

Public Methods

public void addContentView (View view, ViewGroup.LayoutParams params)

Add an additional content view to the screen. Added after any existing ones in the screen — existing views are NOT removed.

Parameters
view The desired content to display.
params Layout parameters for the view.

public void cancel ()

Cancel the dialog. This is essentially the same as calling dismiss() , but it will also call your DialogInterface.OnCancelListener (if registered).

public void closeOptionsMenu ()

See Also

public void dismiss ()

Dismiss this dialog, removing it from the screen. This method can be invoked safely from any thread. Note that you should not override this method to do cleanup when the dialog is dismissed, instead implement that in onStop() .

public boolean dispatchGenericMotionEvent (MotionEvent ev)

Called to process generic motion events. You can override this to intercept all generic motion events before they are dispatched to the window. Be sure to call this implementation for generic motion events that should be handled normally.

Parameters
Returns
  • boolean Return true if this event was consumed.

public boolean dispatchKeyEvent (KeyEvent event)

Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.

Parameters
Returns
  • boolean Return true if this event was consumed.

public boolean dispatchKeyShortcutEvent (KeyEvent event)

Called to process a key shortcut event. You can override this to intercept all key shortcut events before they are dispatched to the window. Be sure to call this implementation for key shortcut events that should be handled normally.

Parameters
Returns
  • True if this event was consumed.

public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)

Called to process population of AccessibilityEvent s.

Parameters
Returns
  • boolean Return true if event population was completed.

public boolean dispatchTouchEvent (MotionEvent ev)

Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Parameters
Returns
  • boolean Return true if this event was consumed.

public boolean dispatchTrackballEvent (MotionEvent ev)

Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.

Parameters
Returns
  • boolean Return true if this event was consumed.

public View findViewById (int id)

Finds a view that was identified by the id attribute from the XML that was processed in onStart() .

Parameters
id the identifier of the view to find
Returns
  • The view if found or null otherwise.

public ActionBar getActionBar ()

Retrieve the ActionBar attached to this dialog, if present.

Returns
  • The ActionBar attached to the dialog or null if no ActionBar is present.

public final Context getContext ()

Retrieve the Context this Dialog is running in.

Returns
  • Context The Context used by the Dialog.

public View getCurrentFocus ()

Call getCurrentFocus() on the Window if this Activity to return the currently focused view.

Returns
  • View The current View with focus or null.
See Also

public LayoutInflater getLayoutInflater ()

public final Activity getOwnerActivity ()

Returns the Activity that owns this Dialog. For example, if showDialog(int) is used to show this Dialog, that Activity will be the owner (by default). Depending on how this dialog was created, this may return null.

Returns
  • The Activity that owns this Dialog.

public final int getVolumeControlStream ()

See Also

public Window getWindow ()

Retrieve the current Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.

Returns
  • Window The current window, or null if the activity is not visual.

public void hide ()

Hide the dialog, but do not dismiss it.

public void invalidateOptionsMenu ()

See Also

public boolean isShowing ()

Returns
  • Whether the dialog is currently showing.

public void onActionModeFinished (ActionMode mode)

Called when an action mode has been finished. The appropriate mode callback method will have already been invoked. Note that if you override this method you should always call through to the superclass implementation by calling super.onActionModeFinished(mode).

Parameters
mode The mode that was just finished.

public void onActionModeStarted (ActionMode mode)

Called when an action mode has been started. The appropriate mode callback method will have already been invoked. Note that if you override this method you should always call through to the superclass implementation by calling super.onActionModeStarted(mode).

Parameters
mode The new mode that has just been started.

public void onAttachedToWindow ()

Called when the window has been attached to the window manager. See View.onAttachedToWindow() for more information.

public void onBackPressed ()

Called when the dialog has detected the user’s press of the back key. The default implementation simply cancels the dialog (only if it is cancelable), but you can override this to do whatever you want.

public void onContentChanged ()

This hook is called whenever the content view of the screen changes (due to a call to Window.setContentView or Window.addContentView ).

public boolean onContextItemSelected (MenuItem item)

See Also

public void onContextMenuClosed (Menu menu)

See Also

public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)

Called when the context menu for this view is being built. It is not safe to hold onto the menu after this method returns.

Parameters
menu The context menu that is being built
v The view for which the context menu is being built
menuInfo Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.
See Also

public boolean onCreateOptionsMenu (Menu menu)

It is usually safe to proxy this call to the owner activity’s onCreateOptionsMenu(Menu) if the client desires the same menu for this Dialog.

See Also

public boolean onCreatePanelMenu (int featureId, Menu menu)

Initialize the contents of the menu for panel ‘featureId’. This is called if onCreatePanelView() returns null, giving you a standard menu in which you can place your items. It is only called once for the panel, the first time it is shown.

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreatePanelMenu() is called for this feature.

Parameters
featureId The panel being created.
menu The menu inside the panel.
Returns
  • boolean You must return true for the panel to be displayed; if you return false it will not be shown.
See Also

public View onCreatePanelView (int featureId)

Instantiate the view to display in the panel for ‘featureId’. You can return null, in which case the default content (typically a menu) will be created for you.

Parameters
featureId Which panel is being created.
Returns
  • view The top-level view to place in the panel.
See Also

public void onDetachedFromWindow ()

Called when the window has been attached to the window manager. See View.onDetachedFromWindow() for more information.

public boolean onGenericMotionEvent (MotionEvent event)

Called when a generic motion event was not handled by any of the views inside of the dialog.

Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. The source of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event. The following code example shows how this is done.

Generic motion events with source class SOURCE_CLASS_POINTER are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.

See onGenericMotionEvent(MotionEvent) for an example of how to handle this event.

Источник

Читайте также:  Плеер для андроида huawei
Оцените статью