- Фоновое изображение в Layout
- Разметка интерфейса
- Изменение положения устройства
- Метод onConfigurationChanged
- Манифест AndroidManifest.xml
- Активность приложения MainActivity
- Положение portrait
- Положение landscape
- Скачать изображения
- Relative Layout Background Color And Image Example In Android Studio
- Adding a background image to an Android Toolbar in the right way
- The final result
- Getting started
- Making the status bar transparent
- Adding a background image to the AppBarLayout
- Styles and Themes
- Themes versus Styles
- Create and apply a style
- Extend and customize a style
- Apply a style as a theme
- Style hierarchy
- TextAppearance
- Customize the default theme
- Add version-specific styles
- Customize widget styles
- Additional resources
- Blog posts
Фоновое изображение в Layout
Android позволяет устанавливать фоновое (background) изображение в корневой элемент разметки интерфейса Layout. Реализовать это совсем просто; достаточно в описание разметки вставить соответствующий атрибут android:background=»@drawable/earth». Предполагается, что изображение earth хранится в директории проекта res/drawable. На следующем скриншоте представлено изображение земли earth.png, которое будет использовано в описанном ниже примере в качестве фонового изображения разметки интерфейса Layout.
В чем особенность данного фонового изображения? Прямоугольный размер картинки включает расположенное не по центру изображение земли, которое при смене ориентации (orientation) будет «сплющиваться». Все правильные фигуры изображения будут изменять геометрические размеры, поскольку android будет непропорционально растягивать или сжимать фоновое изображения. На следующем скриншоте представлено данное фоновое изображение при повороте устройства android в положение portrait.
В этой статье рассмотрим вопросы размещения и адаптации фонового изображения в разметке интерфейса в зависимости от ориентации устройства. Нам необходимо будет научиться перехватывать обработку события при изменении положения устройства, и устанавливать соответствующее его ориентации фоновое изображение разметки.
Рассмотрим пример использования фонового изображения в разметке интерфейса. Нам необходимо :
- определить фоновое изображение в разметке интерфейса;
- подключиться к событию изменения положения/ориентации устройства;
- определить фоновое изображение согласно положению/ориентации устройства.
Создайте новый модуль Module приложения и разместите два изображения (earth_portrait.png, earth_landscape.png) в директории проекта res/drawable. Правильнее было бы, конечно, создать несколько изображений под разные разрешения, о чем сказано в описании ImageView. Но, для решения текущей задачи обойдемся «малой кровью», т.е. двумя изображениями. Изображения можно скачать в конце статьи.
Разметка интерфейса
В файле описания интерфейса приложения res/layout/activity.xml определяем два атрибута : background и orientation. В атрибуте android:background определяем ресурсный файл одного из изображениий. Атрибут android:orientation добавляем в описание разметки LinearLayout, чтобы среда разработки Android Studio не «ругалась».
Изменение положения устройства
Для того, чтобы подключиться к событию изменения положения устройства необходимо переписать метод активности onConfigurationChanged и соответствующим образом определить атрибут configChanges в файле манифеста проекта, чтобы система вызывала этот метод.
Метод onConfigurationChanged
Метод активности onConfigurationChanged в качестве параметра получает значение конфигурации устройства, которое передается родительскому (super) методу. Новое положение устройства сохраняем в переменной orientation и после этого вызываем метод определения фонового изображения setBackgroundImage.
Для чего нам необходима переменная orientation? Давайте представим ситуацию, что в приложении несколько активностей. В одной из активностей положение устройства изменяется, и после этого открывается данная активность. Система вызовет представленный (переопределенный в листинге) метод onResume, в котором будет определяться соответствующее фоновое изображение вызовом метода setBackgroundImage.
Итак, в листинге были переопределены два метода активности : onConfigurationChanged и onResume. Но, чтобы система вызвала метод onConfigurationChanged, необходимо настроить манифест приложения.
Манифест AndroidManifest.xml
В файле манифеста проекта manifests/AndroidManifest.xml необходимо в описании активности определить атрибут configChanges. Как видно в следующем коде атрибут включает 3 значения (keyboardHidden, orientation, screenSize), разделенных символом «или» ‘|’. То есть система будет реагировать на 3 события.
Дополнительную информацию по настройкам манифеста приложений с несколькими активностями, а также для взаимодействия разных приложений между собой можно получить на странице описания намерений Intent.
Активность приложения MainActivity
В активности приложения только определяется первоначальное значение переменной orientation. В листинг не включены представленные выше методы.
После старта приложения можно изменять положение устройства с portrait на landscape и обратно. Переопределенные в активности методы будут корректно устанавливать соответствующие фоновые изображения.
Положение portrait
Положение landscape
Скачать изображения
Используемые в примере изображения можно скачать здесь (742 Kб).
Источник
Relative Layout Background Color And Image Example In Android Studio
Here we show how to change background color and image in Relative Layout with example in Android Studio.
In this example we create a custom layout in which we display two RelativeLayout’s , one is the parent layout and other one is the child layout in which we display two TextView’s. In the background of Parent Relative Layout we set green color and in the background of child RelativeLayout we set a image/drawable. Finally we get the reference of TextView’s in our Activity and then perform setOnClickListener event on TextView’s. Whenever a user click on any TextView the text value is displayed on screen by using a Toast.
Important Note: We can set color or image in the background of RelativeLayout in XML using background attribute or programmatically means in java class using setBackgroundColor() for color and setBackground() method for setting image.
Step 1: Create a new project and name it RelativeLayout’sBackgroundColorAndImage.
Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open xml file and then create a custom layout in which we display two RelativeLayout’s , one is the parent layout and other one is the child layout in which we display two TextView’s. In the background of Parent Relative Layout we set green color and in the background of child RelativeLayout we set an image/drawable.
Step 3: Open src -> package -> MainActivity.java
In this step Firstly we get the reference of TextView’s and then perform setOnClickListener event on TextView’s so Whenever a user click on any TextView the text value is displayed on screen by using a Toast.
Step 4: Open res -> values-> colors.xml
In this step we define the colors (green and white) that used in the background and text color of TextView’s.
Output:
Now run the app and you will see the below output
Источник
Adding a background image to an Android Toolbar in the right way
At first glance it seems pretty easy to add a background drawable to your Android material design Toolbar. However, if your app bar consists of several views (e.g. an additional tab layout) or if you want a transparent status bar, it gets complicated.
The final result
In this tutorial I will show you how to overcome several difficulties in order to implement a layout similar to the following:
Getting started
We start with a new Tabbed Activity with Action Bar Tabs (with ViewPager). Android Studio generates a layout file and the activity which are the perfect start for this project. We just need to make a few optimizations here and there so that it looks like the end result above. The first step is to get rid of the floating action button in your activity_main.xml and in the MainActivity.java code and after that your app should look like this:
With this being your layout file:
Making the status bar transparent
First of all, you need to change your activity theme to have a transparent status bar. Therefore add a theme to your styles.xml:
And set this theme as your activity theme in the AndroidManifest.xml:
This makes almost no difference to the appearance of your app, only the status bar looks a bit darker. However, this is necessary for your background image to be visible below the status bar.
Adding a background image to the AppBarLayout
After that, you need to add your background drawable resource to your layout by adding the following attribute to your AppBarLayout in your activity_main.xml layout file:
You can download the background drawable I am using here as vector graphic which was created in Adobe Illustrator. Unfortunately, the result looks not as good as expected (your layout can differ based on the size of the background image you chose):
There are several issues with your layout:
1. The Toolbar is not transparent so there is a lot of blue (primary color)
2. The image is not visible under our status bar, even though we made it transparent before
3. You can scroll the Toolbar away
4. The app bar layout changed its size based on the background image
To fix the first issue we simply need to remove the android:background=»?attr/colorPrimary» attribute from our Toolbar to make it transparent instead of filled with the primary color.
Furthermore, to fix the second issue we need to add some android:fitsSystemWindows=»true» attributes to our layout since this attribute is not inherited. So add it to your AppBarLayout and to your Toolbar in order to make the AppBarLayout use the space below the status bar and to position your Toolbar just below the status bar. Additionally, remove the android:paddingTop=»@dimen/appbar_padding_top» attribute from your AppBarLayout.
Moreover, to change the third issue remove the app:layout_scrollFlags=»scroll|enterAlways» attribute from your Toolbar.
Last but not least, the Toolbar is way to big because the background drawable is part of the content of the view and the attribute android:layout_height=»wrap_content» is set for your AppBarLayout. Nevertheless, you can’t just change the height of the app bar layout to a fixed value, since the status bar height differs from phone to phone. Luckily, I can tell you the height of a TabLayout which is 48dp high and the height of a Toolbar which is 56dp high. Consequently, our AppBarLayout needs to have the height 48dp+56dp+StatusBarHeight. You need to set this height programmatically in the onCreate method of your MainActivity.java by using the following code:
Just call the method setAppBarHeight in your onCreate method and that’s it!
Finally, your app should now look like this:
Источник
Styles and Themes
Styles and themes on Android allow you to separate the details of your app design from the UI structure and behavior, similar to stylesheets in web design.
A style is a collection of attributes that specify the appearance for a single View . A style can specify attributes such as font color, font size, background color, and much more.
A theme is a collection of attributes that’s applied to an entire app, activity, or view hierarchy—not just an individual view. When you apply a theme, every view in the app or activity applies each of the theme’s attributes that it supports. Themes can also apply styles to non-view elements, such as the status bar and window background.
Styles and themes are declared in a style resource file in res/values/ , usually named styles.xml .
Figure 1. Two themes applied to the same activity: Theme.AppCompat (left) and Theme.AppCompat.Light (right)
Themes versus Styles
Themes and styles have many similarities, but they are used for different purposes. Themes and styles have the same basic structure—a key-value pair which maps attributes to resources.
A specifies attributes for a particular type of view. For example, one style might specify a button’s attributes. Every attribute you specify in a style is an attribute you could set in the layout file. By extracting all the attributes to a style, it’s easy to use and maintain them across multiple widgets.
A defines a collection of named resources which can be referenced by styles, layouts, widgets, and so on. Themes assign semantic names, like colorPrimary , to Android resources.
Styles and themes are meant to work together. For example, you might have a style that specifies that one part of a button should be colorPrimary , and another part should be colorSecondary . The actual definitions of those colors is provided in the theme. When the device goes into night mode, your app can switch from its «light» theme to its «dark» theme, changing the values for all those resource names. You don’t need to change the styles, since the styles are using the semantic names and not specific color definitions.
For more information about how themes and styles work together, see the blog post Android Styling: Themes vs Styles.
Create and apply a style
To create a new style or theme, open your project’s res/values/styles.xml file. For each style you want to create, follow these steps:
You can apply the style to a view as follows:
Each attribute specified in the style is applied to that view if the view accepts it. The view simply ignores any attributes that it does not accept.
Note: Only the element to which you add the style attribute receives those style attributes—any child views do not apply the styles. If you want child views to inherit styles, instead apply the style with the android:theme attribute.
However, instead of applying a style to individual views, you’ll usually apply styles as a theme for your entire app, activity, or collection of views.
Extend and customize a style
When creating your own styles, you should always extend an existing style from the framework or support library so that you maintain compatibility with platform UI styles. To extend a style, specify the style you want to extend with the parent attribute. You can then override the inherited style attributes and add new ones.
For example, you can inherit the Android platform’s default text appearance and modify it as follows:
However, you should always inherit your core app styles from the Android Support Library. The styles in the support library provide compatibility with Android 4.0 (API level 14) and higher by optimizing each style for the UI attributes available in each version. The support library styles often have a name similar to the style from the platform, but with AppCompat included.
To inherit styles from a library or your own project, declare the parent style name without the @android:style/ part shown above. For example, the following example inherits text appearance styles from the support library:
You can also inherit styles (except those from the platform) by extending a style’s name with a dot notation, instead of using the parent attribute. That is, prefix the name of your style with the name of the style you want to inherit, separated by a period. You should usually do this only when extending your own styles, not styles from other libraries. For example, the following style inherits all styles from the GreenText style above and then increases the text size:
You can continue inheriting styles like this as many times as you’d like by chaining on more names.
Note: If you use the dot notation to extend a style, and you also include the parent attribute, then the parent styles override any styles inheritted through the dot notation.
To find which attributes you can declare with an tag, refer to the «XML attributes» table in the various class references. All views support XML attributes from the base View class, and many views add their own special attributes. For example, the TextView XML attributes includes the android:inputType attribute that you can apply to a text view that receives input, such as an EditText widget.
Apply a style as a theme
You can create a theme the same way you create styles. The difference is how you apply it: instead of applying a style with the style attribute on a view, you apply a theme with the android:theme attribute on either the tag or an tag in the AndroidManifest.xml file.
For example, here’s how to apply the Android Support Library’s material design «dark» theme to the whole app:
And here’s how to apply the «light» theme to just one activity:
Now every view in the app or activity applies the styles defined in the given theme. If a view supports only some of the attributes declared in the style, then it applies only those attributes and ignores the ones it does not support.
Beginning with Android 5.0 (API level 21) and Android Support Library v22.1, you can also specify the android:theme attribute to a view in your layout file. This modifies the theme for that view and any child views, which is useful for altering theme color palettes in a specific portion of your interface.
The previous examples show how to apply a theme such as Theme.AppCompat that’s supplied by the Android Support Library. But you’ll usually want to customize the theme to fit your app’s brand. The best way to do so is to extend these styles from the support library and override some of the attributes, as described in the next section.
Style hierarchy
Android provides a variety of ways to set attributes throughout your Android app. For example, you can set attributes directly in a layout, you can apply a style to a view, you can apply a theme to a layout, and you can even set attributes programmatically.
When choosing how to style your app, be mindful of Android’s style hierarchy. In general, you should use themes and styles as much as possible for consistency. If you’ve specified the same attributes in multiple places, the list below determines which attributes are ultimately applied. The list is ordered from highest precedence to lowest:
- Applying character- or paragraph-level styling via text spans to TextView -derived classes
- Applying attributes programmatically
- Applying individual attributes directly to a View
- Applying a style to a View
- Default styling
- Applying a theme to a collection of Views, an activity, or your entire app
- Applying certain View-specific styling, such as setting a TextAppearance on a TextView
Figure 2. Styling from a span overrides styling from a textAppearance .
If you’re trying to style your app and not seeing the results you expect, it’s likely that other styling is overriding your changes. For example, if you apply a theme to your app, along with a style to an individual View , the style attributes would override any matching theme attributes for that View . Note, however, that any theme attributes that aren’t overridden by the style are still used.
TextAppearance
One limitation with styles is that you can apply only one style to a View . In a TextView , however, you can also specify a TextAppearance attribute which functions similarly to a style, as shown in the following example:
TextAppearance allows you to define text-specific styling while leaving a View ’s style available for other uses. Note, however, that if you define any text attributes directly on the View or in a style, those values would override the TextAppearance values.
TextAppearance supports a subset of styling attributes that TextView offers. For the full attribute list, see TextAppearance .
Some common TextView attributes not included are lineHeight[Multiplier|Extra] , lines , breakStrategy , and hyphenationFrequency . TextAppearance works at the character level and not the paragraph level, so attributes that affect the entire layout are not supported.
Customize the default theme
When you create a project with Android Studio, it applies a material design theme to your app by default, as defined in your project’s styles.xml file. This AppTheme style extends a theme from the support library and includes overrides for color attributes that are used by key UI elements, such as the app bar and the floating action button (if used). So you can quickly customize your app’s color design by updating the provided colors.
For example, your styles.xml file should look similar to this:
Notice that the style values are actually references to other color resources, defined in the project’s res/values/colors.xml file. So that’s the file you should edit to change the colors. But before you start changing these colors, preview your colors with the Material Color Tool. This tool helps you pick colors from the material palette and preview how they’ll look in an app.
Once you know your colors, update the values in res/values/colors.xml :
And then you can override whatever other styles you want. For example, you can change the activity background color as follows:
For a list of attributes you can use in your theme, see the table of attributes at R.styleable.Theme . And when adding styles for the views in your layout, you can also find attributes by looking at the «XML attributes» table in the view class references. For example, all views support XML attributes from the base View class.
Most attributes are applied to specific types of views, and some apply to all views. However, some theme attributes listed at R.styleable.Theme apply to the activity window, not the views in the layout. For example, windowBackground changes the window background and windowEnterTransition defines a transition animation to use when the activity starts (for details, see Start an Activity with an Animation).
The Android Support Library also provides other attributes you can use to customize your theme extended from Theme.AppCompat (such as the colorPrimary attribute shown above). These are best viewed in the library’s attrs.xml file
Note: Attribute names from the support library do not use the android: prefix. That’s used only for attributes from the Android framework.
There are also different themes available from the support library that you might want to extend instead of the ones shown above. The best place to see the available themes is the library’s themes.xml file.
Add version-specific styles
If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:
Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a «base» theme and then extending it in your version-specific styles.
For example, to declare window transitions for Android 5.0 (API level 21) and higher, you need to use some new attributes. So your base theme in res/values/styles.xml could look like this:
Now you can apply AppTheme in your manifest file and the system selects the styles available for each system version.
For more information about using alternative resources for different devices, read Providing Resources.
Customize widget styles
Every widget in the framework and support library has a default style. For example, when you style your app using a theme from the support library, an instance of Button is styled using the Widget.AppCompat.Button style. If you’d like to apply a different widget style to a button, then you can do so with the style attribute in your layout file. For example, the following applies the library’s borderless button style:
And if you want to apply this style to all buttons, you can declare it in your theme’s buttonStyle as follows:
You can also extend widget styles, just like extending any other style, and then apply your custom widget style in your layout or in your theme.
Additional resources
To learn more about themes and styles, see the following additional resources:
Blog posts
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник