No window title android

Содержание
  1. Как удалить строку заголовка в студии Android?
  2. No window title android
  3. Советы
  4. Cleartext HTTP traffic not permitted (https)
  5. Запретить делать скриншот экрана приложения
  6. Аналог html-кода
  7. Где находятся исходники системного калькулятора?
  8. Имитация тяжёлых задач
  9. Доступ к ресурсам через URI
  10. Ошибка Debug Certificate expired
  11. Убрать предупреждающие значки при использовании строк в атрибутах
  12. Проверка на первый запуск приложения
  13. Ошибка при загрузке apk-файла на эмулятор/устройство
  14. Сделать скриншот экрана своего приложения
  15. Раскодирование HTML-символов
  16. Кодирование строк по схеме UTF-8
  17. Кодирование в режиме Base64
  18. Пишем собственную функцию md5() для вычисления хэша строки
  19. Как заблокировать экран в приложении?
  20. Узнать размеры экрана
  21. В чем разница между fill_parent и match_parent
  22. Как убрать заголовок у Activity?
  23. Как использовать собственный значок для программы
  24. Получить номер версии программы
  25. Убить приложение
  26. Сколько используется памяти
  27. Разрешённый объём памяти для приложения
  28. Запретить автоматическую смену ориентации при повороте устройства
  29. Dialogs
  30. In this document
  31. Key classes
  32. See also
  33. Avoid ProgressDialog
  34. Creating a Dialog Fragment
  35. Building an Alert Dialog
  36. Adding buttons
  37. Adding a list
  38. Adding a persistent multiple-choice or single-choice list
  39. Creating a Custom Layout
  40. Passing Events Back to the Dialog’s Host
  41. Showing a Dialog
  42. Showing a Dialog Fullscreen or as an Embedded Fragment
  43. Showing an activity as a dialog on large screens
  44. Dismissing a Dialog

Как удалить строку заголовка в студии Android?

В моем приложении эта строка заголовка находится вверху, там, где должно быть дополнительное меню, но мне не нужны настройки, и у меня только один экран. Когда я меняю тему, как описано во многих других вопросах, я получаю старую тему 2.2. Я хочу иметь современную тему только без панели наверху.

Перейдите в styles.xml и измените его .DarkActionBar на .NoActionBar

если цвета не имеют отношения к вашему приложению, вы можете выбрать

В файле манифеста Изменить:

работает onCreate() при setContentView() вызове перед .

иначе он выйдет из строя

В файле styles.xml измените DarkActionBar на NoActionBar

Это работает для меня

В файле манифеста измените на это:

Это работало для меня при values/styles.xml добавлении элементов:

Перейдите в Project -> app -> main -> res -> values ​​-> styles.xml

Измените эту строку, если хотите удалить ее для каждого просмотра

если вы хотите сделать это только для одного представления, вы можете изменить его в своих данных манифеста. Заходим в Android -> манифесты -> AndroidManifest.xml. сделать следующее:

  1. Найдите представление, в котором вы хотите получить изменения этого типа
  2. Добавить android:theme=»»@style/Theme.AppCompat.NoActionBar»

вы можете изменить name = «———«

найти android: theme = «@ style / AppTheme» измененный на android: theme = «@ style / no_title»

нажмите выбрать тему в строке меню (зеленый цвет рядом с MainActivity)

  • нажмите тема проекта
  • щелкните no_title (справа от вас)
  • нажмите ОК

Источник

No window title android

Полный текст статьи и исходники программы доступны только зарегистрированным участникам сайта.

Прочитайте внимательно условия! В начале каждой статьи указывается, к какому курсу относится данная статья. Например, если статья из 4 курса, значит нужно заплатить за все курсы по четвёртый включительно.

Стоимость регистрации — символические 350 рублей. После регистрации у вас будет доступ ко второму курсу.

Для регистрации сначала необходимо пополнить ЮMoney(бывший Яндекс.Кошелек) 410011383280263 на указанную сумму (или Webmoney-кошелек P894989790291 (старый R390884954122) или QIWI (перевод по никнейму), а затем прислать письмо на адрес alexander.klimoff@gmail.com с указанием, на какой кошелёк вы делали оплату и реквизиты, по которым можно вас определить (не прикрепляйте к письму картинки или файлы). Учитывайте комиссию при переводах.

Не присылайте в письме мои номера кошельков — поверьте, я их знаю и без вас.

В ответном письме вы получите учётные данные для чтения статей из закрытой зоны за второй курс.

Доступ к третьему курсу обучения доступен только после оплаты второго курса и составляет 350 руб.

Доступ к четвёртому курсу обучения доступен после оплаты третьего курса и составляет 350 руб. и т.д.

При оплате сразу всех курсов одновременно (2-9) цена составит 2800 руб.

Доступ даётся как минимум на один год. Для тех, кто оплатил третий и другие курсы, сроки доступа увеличиваются.

Также возможен приём на PayPal (только для зарубежных пользователей). Обратите внимание, что в этом случае стоимость одного курса составляет 7$.

Источник

Советы

Cleartext HTTP traffic not permitted (https)

При работе с Android 8+ примеры, которые обращаются к веб-адресам по протоколу http вызывают ошибку. Чтобы обойти данное ограничение, можно сделать следующее.

В папке res/xml размещаем файл network_security_config.xml:

В манифесте в блоке application добавляем новый атрибут.

Запретить делать скриншот экрана приложения

Существует специальный флаг FLAG_SECURE, запрещающий пользователю сделать скриншот вашего экрана. Это нужно в целях безопасности для отдельных видов приложений, например, банковских.

Аналог html-кода

При многострочных текстах вы можете воспрепятствовать переносу слов на разные строки, если их желательно держать вместе. В html есть специальный символ неразрывного пробела . В строковых ресурсах вы можете использовать символ или юникод-код \u00A0.

Где находятся исходники системного калькулятора?

Имитация тяжёлых задач

В Android нельзя выполнять сложные задачи в основном потоке. Для создания быстрой заглушки, которая будет имитировать тяжёлую задачу, можно написать следующий код:

Например, поместите код в обработчик нажатия кнопки и после нажатия нажмите на кнопку Back. Программа зависнет и вы увидите сообщение об этом.

Доступ к ресурсам через URI

Обычно мы обращаемся к ресурсам через идентификатор. Существует альтернативный способ через Uri. Например, такой подход может пригодиться для загрузки изображения в WebView при помощи метода loadUrl(). Формат доступа будет следующим: android.resource://[package-name]/res-id. Например:

Ошибка Debug Certificate expired

По умолчанию вашей программе выдается отладочный сертификат на один год. Если у вас есть старый проект, то можете получить сообщение об ошибке: Error generating final archive: Debug Certificate expired.

Вам следует удалить старый сертификат, и Eclipse создаст новый ещё на один год. Путь к сертификату можно посмотреть в настройках: Preferences | Android | Build | Default debug keystore. Обычно это папка C:\Users\ИмяПользователя\.android.

Убрать предупреждающие значки при использовании строк в атрибутах

Если в некоторых атрибутах компонентов использовать строки, то появляются предупреждающие значки с всплывающей надписью [I18N] Hardcoded string «Котики рулят», should use @string resource. Надпись призывает использовать строковые ресурсы, а не писать текст прямо в атрибутах. На самом деле это всего лишь предупреждение, а не ошибка. Программа будет прекрасно запускаться, но новичков такие надписи пугают. Можете убрать данное предупреждение, если добавите дополнительный атрибут tools:ignore.

Читайте также:  Андроид для компьютера ноутбука

Проверка на первый запуск приложения

Для проверки первого запуска приложения можно использовать настройки SharedPreferences. Смотрите пример.

Ошибка при загрузке apk-файла на эмулятор/устройство

Если при загрузке apk-файла вашего приложения на эмулятор или устройство вы получаете сообщение об ошибке:

Failed to upload xxxxxxxx.apk on device ’emulator-5554′
java.io.IOException: Unable to upload file: timeout

То зайдите в Eclipse в меню Window | Preferences | Android | DDMS и в текстовом поле ADB connection time-out (ms) вместо значения по умолчанию 5000 введите большее значение.

Сделать скриншот экрана своего приложения

Один из примеров снятия скриншота своего экрана — через методы рисования получить графический отпечаток корневой разметки, а затем сохранить его как картинку, которую можно вывести в ImageView. Выберите любой ваш экран для опытов и добавьте на неё кнопку для снятия скриншотов и ImageView для вывода сохранённого изображения. В моём случае корневым элементом была компоновка TableLayout.

Результат до и после снятия скриншота. Сам скриншот помещается в ImageView, поэтому растягивается до его размеров. Попробуйте доработать пример.

Изменённый пример, когда скриншот сохраняется на SD-карту:

Не забываем про разрешения.

Раскодирование HTML-символов

Если вам нужно раскодировать HTML-символы (угловые скобки <>, знак амперсанда &, кавычки «»), то воспользуйтесь методом TextUtils.htmlEncode(). Добавим на форму две текстовые метки. И небольшой код для примера:

Примечание: Если вы пользуетесь Notepad++, то там есть такая же возможность: TextFX | TextFX Convert | Encode HTML.

Кодирование строк по схеме UTF-8

Вероятно, вы не раз замечали, что в адресной строке некоторые символы заменяются на последовательность других символов. Самый простой пример — символ пробела заменяется на %20. Немного изменим предыдущий пример:

В нашем примере были преобразованы символы пробела и русские символы.

Кодирование в режиме Base64

Пишем собственную функцию md5() для вычисления хэша строки

У PHP-программистов есть готовая функция md5(), которая вычисляет MD5 хэш строки с использованием алгоритма MD5 RSA Data Security и возвращает этот хэш. Хэш представляет собой 32-значное шестнадцатеричное число. Напишем собственную функцию на Java:

Осталось применить её где-нибудь:

Как заблокировать экран в приложении?

Также нужно установить разрешение android.permission.DISABLE_KEYGUARD.

Если стоит обратная задача — запретить блокировку экрана при долгом бездействии, то используйте метод setKeepScreenOn() или используйте XML-атрибут android:keepScreenOn=»true».

Узнать размеры экрана

Для вычисления размеров экрана можно воспользоваться двумя способами. Второй способ более правильный.

В чем разница между fill_parent и match_parent

match_parent = fill_parent. Первое свойство нужно использовать в новых проектах, второе свойство считается устаревшим и пока оставлено в целях совместимости.

Как убрать заголовок у Activity?

В некоторых случаях хочется спрятать заголовок (Title) у программы. Есть несколько способов. Например, применить специальную тему (прописать в манифесте файла):

Также попробуйте android:theme=»@android:style/Theme.Black.NoTitleBar.Fullscreen» (убирает не только заголовок, но и панель уведомлений). Названия тем могут быть и другими, смотрите документацию. Несколько примеров

Если у вас используется своя тема, то используйте в ней параметр:

Также существует программный способ (перед вызовом setContentView):

Как использовать собственный значок для программы

Когда вы создаете учебные примеры, то у всех программ используется стандартный значок с изображением андроида. Как же использовать свой значок? Ответ прост. В папке проекта /res вы можете видеть подпапки drawable-ldpi, drawable-mdpi, drawable-hdpi и др., в которых и содержатся готовые значки в формате PNG под разные размеры экранов.

Вы можете просто открыть png-файл в графическом редакторе и нарисовать что-то свое и сохранить изменения.

Вы можете сохранить значки под своим именем, например, cat.png. В этом случае вам надо открыть файл манифеста, найти там строчку:

И отредактировать её, например, android:icon=»@drawable/cat» (без расширения). Как вариант, вы можете сохранить один значок в папке drawable в нужном размере, если пишете программу под определенные типы телефонов.

Размеры значков в папках (часть):

  • Low density – ldpi = 36×36 px
  • Medium density – mdpi = 48×48 px
  • High density – hdpi = 72×72 px
  • Extra-high density screen — xhdpi (320 dpi) = 96 × 96 px

Получить номер версии программы

Убить приложение

Сколько используется памяти

Нужно от общей памяти отнять свободную память

Более общий пример:

Разрешённый объём памяти для приложения

Система выделяет каждому приложению определённый лимит памяти. На разных устройствах размер выделяемой памяти отличается. Чтобы узнать размер выделяемой памяти для вашего приложения, используйте код:

Особенно это касается приложений, которые активно используют графику. Следите за размерами изображений, вызывайте метод recycle() для освобождения памяти при работе с классом BitmapFactory.

Начиная с Android 3.0 можно попросить у системы выделять чуть больше памяти, прописав в манифесте просьбу:

Запретить автоматическую смену ориентации при повороте устройства

Если вы хотите запретить автоматическую смену ориентацию при повороте устройства, то можно ее отключить для нужного экрана. Например, если экран с настройками должен отображаться только в портретном режиме, то добавьте одну строчку с атрибутом screenOrientation в манифест файла для соответствующей активности

Источник

Dialogs

In this document

Key classes

See also

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

Dialog Design

For information about how to design your dialogs, including recommendations for language, read the Dialogs design guide.

The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly. Instead, use one of the following subclasses:

AlertDialog A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog A dialog with a pre-defined UI that allows the user to select a date or time.

Avoid ProgressDialog

Android includes another dialog class called ProgressDialog that shows a dialog with a progress bar. However, if you need to indicate loading or indeterminate progress, you should instead follow the design guidelines for Progress & Activity and use a ProgressBar in your layout.

Читайте также:  Android launcher для java

These classes define the style and structure for your dialog, but you should use a DialogFragment as a container for your dialog. The DialogFragment class provides all the controls you need to create your dialog and manage its appearance, instead of calling methods on the Dialog object.

Using DialogFragment to manage the dialog ensures that it correctly handles lifecycle events such as when the user presses the Back button or rotates the screen. The DialogFragment class also allows you to reuse the dialog’s UI as an embeddable component in a larger UI, just like a traditional Fragment (such as when you want the dialog UI to appear differently on large and small screens).

The following sections in this guide describe how to use a DialogFragment in combination with an AlertDialog object. If you’d like to create a date or time picker, you should instead read the Pickers guide.

Note: Because the DialogFragment class was originally added with Android 3.0 (API level 11), this document describes how to use the DialogFragment class that’s provided with the Support Library. By adding this library to your app, you can use DialogFragment and a variety of other APIs on devices running Android 1.6 or higher. If the minimum version your app supports is API level 11 or higher, then you can use the framework version of DialogFragment , but be aware that the links in this document are for the support library APIs. When using the support library, be sure that you import android.support.v4.app.DialogFragment class and not android.app.DialogFragment .

Creating a Dialog Fragment

You can accomplish a wide variety of dialog designs—including custom layouts and those described in the Dialogs design guide—by extending DialogFragment and creating a AlertDialog in the onCreateDialog() callback method.

For example, here’s a basic AlertDialog that’s managed within a DialogFragment :

Figure 1. A dialog with a message and two action buttons.

Now, when you create an instance of this class and call show() on that object, the dialog appears as shown in figure 1.

The next section describes more about using the AlertDialog.Builder APIs to create the dialog.

Depending on how complex your dialog is, you can implement a variety of other callback methods in the DialogFragment , including all the basic fragment lifecycle methods.

Building an Alert Dialog

The AlertDialog class allows you to build a variety of dialog designs and is often the only dialog class you’ll need. As shown in figure 2, there are three regions of an alert dialog:

Figure 2. The layout of a dialog.

This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you need to state a simple message or question (such as the dialog in figure 1), you don’t need a title.
Content area

This can display a message, a list, or other custom layout.

There should be no more than three action buttons in a dialog.

The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with these kinds of content, including a custom layout.

The following topics show how to define various dialog attributes using the AlertDialog.Builder class.

Adding buttons

To add action buttons like those in figure 2, call the setPositiveButton() and setNegativeButton() methods:

The set. Button() methods require a title for the button (supplied by a string resource) and a DialogInterface.OnClickListener that defines the action to take when the user presses the button.

There are three different action buttons you can add:

Positive You should use this to accept and continue with the action (the «OK» action). Negative You should use this to cancel the action. Neutral You should use this when the user may not want to proceed with the action, but doesn’t necessarily want to cancel. It appears between the positive and negative buttons. For example, the action might be «Remind me later.»

You can add only one of each button type to an AlertDialog . That is, you cannot have more than one «positive» button.

Figure 3. A dialog with a title and list.

Adding a list

There are three kinds of lists available with the AlertDialog APIs:

  • A traditional single-choice list
  • A persistent single-choice list (radio buttons)
  • A persistent multiple-choice list (checkboxes)

To create a single-choice list like the one in figure 3, use the setItems() method:

Because the list appears in the dialog’s content area, the dialog cannot show both a message and a list and you should set a title for the dialog with setTitle() . To specify the items for the list, call setItems() , passing an array. Alternatively, you can specify a list using setAdapter() . This allows you to back the list with dynamic data (such as from a database) using a ListAdapter .

If you choose to back your list with a ListAdapter , always use a Loader so that the content loads asynchronously. This is described further in Building Layouts with an Adapter and the Loaders guide.

Note: By default, touching a list item dismisses the dialog, unless you’re using one of the following persistent choice lists.

Figure 4. A list of multiple-choice items.

Adding a persistent multiple-choice or single-choice list

To add a list of multiple-choice items (checkboxes) or single-choice items (radio buttons), use the setMultiChoiceItems() or setSingleChoiceItems() methods, respectively.

For example, here’s how you can create a multiple-choice list like the one shown in figure 4 that saves the selected items in an ArrayList :

Although both a traditional list and a list with radio buttons provide a «single choice» action, you should use setSingleChoiceItems() if you want to persist the user’s choice. That is, if opening the dialog again later should indicate what the user’s current choice is, then you create a list with radio buttons.

Читайте также:  Образ android для raspberry pi

Creating a Custom Layout

Figure 5. A custom dialog layout.

If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.

By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.

For example, here’s the layout file for the dialog in Figure 5:

Tip: By default, when you set an EditText element to use the «textPassword» input type, the font family is set to monospace, so you should change its font family to «sans-serif» so that both text fields use a matching font style.

To inflate the layout in your DialogFragment , get a LayoutInflater with getLayoutInflater() and call inflate() , where the first parameter is the layout resource ID and the second parameter is a parent view for the layout. You can then call setView() to place the layout in the dialog.

Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the manifest element:

That’s it. The activity now displays in a dialog window instead of fullscreen.

Passing Events Back to the Dialog’s Host

When the user touches one of the dialog’s action buttons or selects an item from its list, your DialogFragment might perform the necessary action itself, but often you’ll want to deliver the event to the activity or fragment that opened the dialog. To do this, define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog.

For example, here’s a DialogFragment that defines an interface through which it delivers the events back to the host activity:

The activity hosting the dialog creates an instance of the dialog with the dialog fragment’s constructor and receives the dialog’s events through an implementation of the NoticeDialogListener interface:

Because the host activity implements the NoticeDialogListener —which is enforced by the onAttach() callback method shown above—the dialog fragment can use the interface callback methods to deliver click events to the activity:

Showing a Dialog

When you want to show your dialog, create an instance of your DialogFragment and call show() , passing the FragmentManager and a tag name for the dialog fragment.

The second argument, «missiles» , is a unique tag name that the system uses to save and restore the fragment state when necessary. The tag also allows you to get a handle to the fragment by calling findFragmentByTag() .

Showing a Dialog Fullscreen or as an Embedded Fragment

You might have a UI design in which you want a piece of the UI to appear as a dialog in some situations, but as a full screen or embedded fragment in others (perhaps depending on whether the device is a large screen or small screen). The DialogFragment class offers you this flexibility because it can still behave as an embeddable Fragment .

However, you cannot use AlertDialog.Builder or other Dialog objects to build the dialog in this case. If you want the DialogFragment to be embeddable, you must define the dialog’s UI in a layout, then load the layout in the onCreateView() callback.

Here’s an example DialogFragment that can appear as either a dialog or an embeddable fragment (using a layout named purchase_items.xml ):

And here’s some code that decides whether to show the fragment as a dialog or a fullscreen UI, based on the screen size:

For more information about performing fragment transactions, see the Fragments guide.

In this example, the mIsLargeLayout boolean specifies whether the current device should use the app’s large layout design (and thus show this fragment as a dialog, rather than fullscreen). The best way to set this kind of boolean is to declare a bool resource value with an alternative resource value for different screen sizes. For example, here are two versions of the bool resource for different screen sizes:

Then you can initialize the mIsLargeLayout value during the activity’s onCreate() method:

Showing an activity as a dialog on large screens

Instead of showing a dialog as a fullscreen UI when on small screens, you can accomplish the same result by showing an Activity as a dialog when on large screens. Which approach you choose depends on your app design, but showing an activity as a dialog is often useful when your app is already designed for small screens and you’d like to improve the experience on tablets by showing a short-lived activity as a dialog.

To show an activity as a dialog only when on large screens, apply the Theme.Holo.DialogWhenLarge theme to the manifest element:

For more information about styling your activities with themes, see the Styles and Themes guide.

Dismissing a Dialog

When the user touches any of the action buttons created with an AlertDialog.Builder , the system dismisses the dialog for you.

The system also dismisses the dialog when the user touches an item in a dialog list, except when the list uses radio buttons or checkboxes. Otherwise, you can manually dismiss your dialog by calling dismiss() on your DialogFragment .

In case you need to perform certain actions when the dialog goes away, you can implement the onDismiss() method in your DialogFragment .

You can also cancel a dialog. This is a special event that indicates the user explicitly left the dialog without completing the task. This occurs if the user presses the Back button, touches the screen outside the dialog area, or if you explicitly call cancel() on the Dialog (such as in response to a «Cancel» button in the dialog).

As shown in the example above, you can respond to the cancel event by implementing onCancel() in your DialogFragment class.

Источник

Оцените статью