- Диалоговые окна в Android. Часть 1
- Android opening context menu after button click
- 4 Answers 4
- Dialog
- Class Overview
- Developer Guides
- Summary
- Public Constructors
- public Dialog (Context context)
- public Dialog (Context context, int theme)
- Protected Constructors
- protected Dialog (Context context, boolean cancelable, DialogInterface.OnCancelListener cancelListener)
- Public Methods
- public void addContentView (View view, ViewGroup.LayoutParams params)
- public void cancel ()
- public void closeOptionsMenu ()
- public void dismiss ()
- public boolean dispatchGenericMotionEvent (MotionEvent ev)
- public boolean dispatchKeyEvent (KeyEvent event)
- public boolean dispatchKeyShortcutEvent (KeyEvent event)
- public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)
- public boolean dispatchTouchEvent (MotionEvent ev)
- public boolean dispatchTrackballEvent (MotionEvent ev)
- public View findViewById (int id)
- public ActionBar getActionBar ()
- public final Context getContext ()
- public View getCurrentFocus ()
- public LayoutInflater getLayoutInflater ()
- public final Activity getOwnerActivity ()
- public final int getVolumeControlStream ()
- public Window getWindow ()
- public void hide ()
- public void invalidateOptionsMenu ()
- public boolean isShowing ()
- public void onActionModeFinished (ActionMode mode)
- public void onActionModeStarted (ActionMode mode)
- public void onAttachedToWindow ()
- public void onBackPressed ()
- public void onContentChanged ()
- public boolean onContextItemSelected (MenuItem item)
- public void onContextMenuClosed (Menu menu)
- public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
- public boolean onCreateOptionsMenu (Menu menu)
- public boolean onCreatePanelMenu (int featureId, Menu menu)
- public View onCreatePanelView (int featureId)
- public void onDetachedFromWindow ()
- 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 |
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 Constructorspublic Dialog (Context context)Create a Dialog window that uses the default dialog frame style. Parameters
public Dialog (Context context, int theme)Create a Dialog window that uses a custom dialog style. Parameters
Protected Constructorsprotected Dialog (Context context, boolean cancelable, DialogInterface.OnCancelListener cancelListener)Public Methodspublic 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
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 Alsopublic 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. ParametersReturns
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. ParametersReturns
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. ParametersReturns
public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)Called to process population of AccessibilityEvent s. ParametersReturns
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. ParametersReturns
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. ParametersReturns
public View findViewById (int id)Finds a view that was identified by the id attribute from the XML that was processed in onStart() . Parameters
Returns
public ActionBar getActionBar ()Retrieve the ActionBar attached to this dialog, if present. Returns
public final Context getContext ()Retrieve the Context this Dialog is running in. Returns
public View getCurrentFocus ()Call getCurrentFocus() on the Window if this Activity to return the currently focused view. Returns
See Alsopublic 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
public final int getVolumeControlStream ()See Alsopublic 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
public void hide ()Hide the dialog, but do not dismiss it. public void invalidateOptionsMenu ()See Alsopublic boolean isShowing ()Returns
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
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
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 Alsopublic void onContextMenuClosed (Menu menu)See Alsopublic 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
See Alsopublic 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 Alsopublic 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
Returns
See Alsopublic 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
Returns
See Alsopublic 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. Источник |