Что такое r в android studio
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
In every instance in all of my classes where I reference R.id.something , the R is in red and it says "cannot resolve symbol R". Also every time there is R.layout.something it is underlined in red and says "cannot resolve method setContentView(?)". The project always builds fine. It is annoying to see this all the time. I have read many other questions on here about something similar but most involved importing projects from Eclipse. I am using what I believe to be the most recent version of Android Studio and the project was created with Android Studio and worked without any "cannot resolve R" problems. I would like to know what causes this if anyone knows.
in the past I have gotten xml errors such as : progressbar cannot be cast to android.widget.textview, and i fixed that by just changing the name of the textview. I still really dont know what caused the error to begin with.
If u changed the name, perhaps you are now trying to use a string reference that does not exist in res/strings.xml?
i searched many times before asking this question and found many similar questions including the one you mentioned. i did read the suggestion in that question and there is no import Android.R in any of my java files.
Hey everyone I forgot about asking this question since it was asked so long ago. I should have accepted my own answer a year ago that is now the comment above this. The issue was with simply that android studio was in such an early stage at the time and as a new developer I never should have never been using it. Rest assured everything is working fine now and has been. If it is possible please undelete my original answer so I can accept it.
Not finding R isnt your error its an error caused by a Build fault Fix your other errors and you should be fine.
96 Answers 96
I had this this issue too. A simple 'gradlew clean' and 'gradlew build' did the trick.
Click on Build->Clean Project and that will perform a gradle clean
For those who convulse over using the command line, click on Build->Clean Project and that will perform a 'gradlew clean'. ;)
In the latest versions of Android Studio, at least for me, the following works:
"Tools" -> "Android" -> "Sync Project with Gradle Files"
In latest Android Studio 3.1.3 (July 2018), "Sync Project with Gradle Files" is available in main menu bar.
I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.
Problem resolved after changing the gradle version. Details history can be found here.
Yet another amazing feat by Android studio developers. Reverting back to 3.2.1 was actually the only solution that has worked for me.
Instead of moving back to gradle 3.2.1 you can also upgrade Android Studio to version 3.3 . See my answer here
it worked by changing 3.3.0 to 3.2.1 but my question it was working fine on 3.3.0 i had just refactor and updated manifest xml file and gradle file and had sync the gradle . May i know what might be the reason
I have a similar problem and here is what I did:
Clean Project and Sync Project with Gradle ,
check buildTools version in my sdk
From build gradle (module ) change minSdkVersion from 8 to 9
But all this didn't help.
Finally I found the answer (this worked in my case)
Change from build.gradle(module:app)
Select File | Project Structure change Build Tools Version to 21.1.1
For example I had an entry in my strings.xml :
And in activity_main.xml I used this string entry
While'd been working with project, I deleted that
And consequently activity_main.xml became not valid. As the result: cannot resolve R.
So, check your *.xml files and clean project.
A missing image one of my XMLs referred to caused this issue for me. Put the image in the folder, cleaned and R is now happy again.
I accidentally had my string defined twice in strings.xml. Studio didn't show that at all. X-( Thank you for your answer.
When something like you mentioned occurs, the issue gets highlighted in the xml. I've tried everything I could find in the internet, but nothing solves my problem, although the app runs normally.
If you see this error after moving java files or directories to other locations, then you can guarantee that Android Studio has gotten confused. And guess what? undo-ing those actions doesn't fix the problem.
So you try a clean, but that doesn't work.
And restarting doesn't work either.
But try File -> Invalidate Caches / Restart. -> Invalidate and Restart
Android Studio maintains information about which files are dependent on which other files. And since moving files around is not implemented correctly, moving files causes errors. And that's not all: caches of these dependencies are used in an attempt to speed up the build.
This means you not only have to restart, but you need to invalidate those caches to restore (or more accurately, rebuild) sanity.
Did not help. Tried cleaning/rebuilding too. Error occured after I moved java package into another package. Interestingly, in one package R class can be accessed, but it cannot be accessed in package that I moved.
In the more recent versions of Android Studio, Invalidate and Restart are now the default menu selection. This should help at least a few people. (Too bad they don't fix all the crazy bugs that cause this error in the first place!)
I got this error after moving and renaming a project. This solved the R problem after all cleaning and restarting did not. Thank you.
This is definitely the right answer if you have first tried 1.)Clean & Rebuild 2.)Ensuring your xml files are valid
I think if you put your Activities files to another folder than the default one. You need to import the com.example.yourproject.R (this is your project R file NOT Android.R file) to ALL activities using R . For example, in MainActivity file insert this line:
Ah, and there will be still error message before you first build. However, you just press build, Android Studio will generate the R file and the build should success.
and I think it's better that after the fix, you should clean your project and then build. or press Shift + F9 for debug with your device or emulator. I prefer to debug on real device.
There seems to be many causes for this issue. Recently, I added an activity to test with called NewActivity. This created a file called res/menu/new.xml and gradle did not like that name because new is a reserved word.
"Tools" -> "Android" -> "Sync Project with Gradle Files"
Those are definitely good things to try, but you may have some other issues you need to resolve before you run those commands.
thanks worked for me too. Small question - where should i type gradlew clean if i want to do it this way (i did "Tools" -> "Android" -> "Sync Project with Gradle Files")?
Yes, in my case I added a png file, called "import.jpg". I had to rename it, in my case "import_icon.jpg" and then the project compiled ok.
R.java file contains the link between xml and java page. "R cannot be resolved" arise only if there is a problem with some of your resource files. So the best and effective way is delete the last done xml or drawable in res file. and then again start from there according to android coding norms. This is the only way. The effective and right way.
Also use Git for proper tracking of code. ..
Your code is just scrambled. The answer is fairly simple.
Just go to Build --> Clean Project.
That should do the trick.
Check also your version of Android Studio.
I'm currently using Android Studio 3.0.1.
Have you updated your SDK tools recently? Launch the android SDK manager and make sure you have the latest SDK tools, which is now separate from the platform tools. I had this same issue when I first updated my SDK manager, the SDK build tools package did not show up for install/update until I closed and reopened the SDK manager.
I had to import my R package in android studio. For ex: import com.example..R
This happened to me after I refactored my package name, but somehow the android studio left the import com.example.old-package-name.R , so I had to rename the import.
I had moved some UI stuff to a sub-package and then got the error, I needed to import R from the parent package.
Just clean your project and Sync Project with Gradle File.
And the problem will be resolved.
It should be noted that right clicking on "app" and clicking the synchronise button in the menu does not achieve this. Thanks.
I have had this with
- An uppercase letter in my drawable resources.
- Import Android.R being added by Android Studio (or Eclipse)
- Error in xml file
I had the issue because there was an error in one of my XML files. Resolved the issue then did a Build->Clean Project
I recently had this issue and the clean/build etc. didn't resolve it. I guessed I had an issue somewhere but wasn't sure where to look to find it (was it in the manifest, resource xml files etc?).
When something is wrong, you can find out what it is by doing a code analysis run.
From the menu at the top choose:
Analyze -> Inspect code, scan the whole project using the 'Default' profile.
Your inspection results will contain an element called 'Android'. In here you will get a list of anything that is causing issues in your resources and manifest file. The errors will open up the generated xml files from your build which will show any errors in red.
My exact issue was caused because I was using flavour based manifest files and I copied some permissions inside the tag in the flavour by accident.
UPDATE: I did have an issue after where Android Studio still showed the error after the fix, even though I could now build and run perfectly fine while the error was still there. (I am running a canary build so putting it down to that for now)
Interestingly, I had this issue on just one file and ran the "Inspect Code" process and it cleared itself (clean and rebuild didn't fix it). There must have been something stuck in Lint that only this could clear out. Thanks!
Thank you for this! While this found many general errors, which was expected, the piece that brought down the entire castle was a small Syntax error in an XML file generated by Asset Studio! Once I resolved this, a Clean Project allowed me to move forward.
You should do two things, first clean the project (in build menu) - it deletes the build directory which may be the culprit:
Next, Sync project with Gradle files (under file):
This is the placement for the items in Android Studio 3.6.1 on Windows 10.
If all else fails, Invalidate Caches and Restart (under file) usually does the trick. This closes down the whole program and takes the most amount of time, in my opinion.
To clarify, I am running this on windows 10, but it should work on MacOS and Linux as well.
I faced this issue when I manually renamed the domain folder of my app. To fix this issue, I had to
- Set the proper package folder structure of in AndroidManifest.xml .
- Set the new package location for android:name of in AndroidManifest.xml .
- Clear cache by
File Menu -> Invalidate Caches / Restart .
The issue will be gone, once the Android studio restarts and builds the fresh index.
I had the same issue: Android Studio 3.2 The project compiles and runs fine, but I am getting "Cannot resolve symbol "R" on-screen warnings
Does not help:
- Build->Clean Project
- Build->Rebuild Project
- File->Invalidate Caches/Restart
Update Android Studio to 3.3
This is a very old question, but it still happens a lot and there is no truly comprehensive answer here.
I have had this problem more times than I want to admit. It can be caused by a wide variety of issues that mostly all have to do with your project structure not matching what's expected. Here's a list of all the problems I've had:
Importing from Eclipse to Android Studio does not always work smoothly, especially with older versions of Android Studio. Make sure you're using the correct directory tree. It should look like this for a moderately mature app:
It may not look like this in your IDE. There is a drop-down above the file tree that displays your files in different ways, and it defaults on my system to one called Android that breaks your files out into their different types. It's easier to fix this kind of problem from the one called Project, and even easier directly from your OS's file system, because Android Studio collapses folders that only contain another folder onto a single line.
Especially if you ever change the name of your app, you need to make sure that the source tree main/java/com/domain/AppName is updated. Also make sure that the package tag in your AndroidManifest.xml is correct.
If there are errors in either your Gradle files or your AndroidManifest.xml, this will prevent Android Studio from properly building your resource files. Gradle files can be broken by upgrading Android Studio sometimes, especially from the pre-1.0 versions. Sometimes this is because it stops supporting older versions of the Gradle plugin, so you need to update your version numbers. It can sometimes be hard to find what the current versions are. As of today, 7/17/15, my apps are compiling fine with com.android.tools.build:gradle:1.2.3 . This is in the dependencies block in the outermost gradle file,
If your AndroidManifest references a non-existent drawable or string resource or activity, it will break and cause this error. Sometimes if anything references a nonexistent drawable or string resource you will get this error.
If you have a file in your resources that is corrupted, or an invalid xml file, you will get this error.
In my experience, sometimes Android Studio just hiccups for no reason, and you need to restart it and/or your PC. I don't know why, but sometimes it works.
If you have two xml resources with the same name, in directories that do not override each other, you can have this problem. For instance, you can have the same name in drawable-mhdpi and drawable-xhdpi because they override each other depending on the target device, but if you have the same name in layout and in menu, it will cause a problem. Rename or delete one of the files.
If only some resources are having this problem, those resources are most likely in the wrong directory.
In one case I had to completely reinstall Android Studio. I don't know what was wrong, but it worked.
In one case I moved my entire project to a different directory and re-imported it as a new project. I don't know what was wrong, but it worked.
Xml files with reserved words for names can cause this problem. Rename or delete them.
There are a few ways your Gradle file can end up referencing a version of the build-tools that you do not have installed. Correct this by changing Gradle or downloading the appropriate build-tools.
Finally, after you've fixed whatever is wrong, you need to clean your Gradle project. You do this by going to the Build menu at the top and selecting Clean Project.
In AndroidStudio, when I create a project using an empty activity, I get the following piece of code in the MainActivity.java file:
where a cryptic class named R is used. What is the purpose of this class R ?
Использование ресурсов в коде
Для использования ресурса в коде нужно знать только полный ID ресурса и в какой тип объекта Ваш ресурс был откомпилирован. Вот синтаксис обращения к ресурсу:
R.resource_type.resource_nameт или android.R.resource_type.resource_name
resource_type - подкласс R, который содержит определенный тип ресурса. resource_name - атрибут ресурсов, определенный в файлах XML, или имя файла (без расширения) для ресурса, определенных другими типами файла. Каждый тип ресурса будет добавлен в подкласс R, в зависимости от его типа.
Ресурсы, откомпилированные Вашим приложением, могут быть использованы без названия пакета (просто как R.resource_type.resource_name). Андроид содержит многие стандартные ресурсы, такие как стили экрана и фоны кнопки. Обращаться к ним в коде Вы можете через android.R.resource_type.resource_name, для примера: android.R.drawable.button_background.
Not the answer you're looking for? Browse other questions tagged java android or ask your own question.
Linked
Related
Hot Network Questions
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.5.10.42085
Ресурсы - внешние файлы (не код), которые используются Вашим кодом, закомпилированы в Ваше приложение и встраиваются в него во время работы. Андроид поддерживает многие различные виды файлов ресурсов, включая XML, PNG и JPEG. Файлы XML имеют сильно различающиеся форматы в зависимости от того, что они описывают. Ресурсы описаны в исходном коде, и файлы XML откомпилированы в двоичный код для быстрой и эффективной загрузки. Строки сжаты в более форму, более экономящую память.
Список ресурсов
Типы ресурсов и их местоположение:
- стили, строки и массивы - “/res/values/” .
- Названия не могут отличаться:
- ‘arrays.xml’ для определения массивов.
- ‘colors.xml’ для определения цветов.
- ‘dimens.xml’ для определения размеров (dimensions).
- ‘strings.xml’ для определения строк.
- ‘styles.xml’ для определения стилей объектов.
- необработанные файлы вроде mp3 или видео - “/res/raw/”
Восстановление данных с жесткого диска
Основной функцией программы является восстановление потерянных данных.
Чтобы найти удаленный файл, можно сначала просмотреть содержимое раздела диска, где он раньше размещался. Для этого, кликаем по наименованию раздела диска, и жмем на кнопку в верхней панели «Показать содержимое диска».
Начинается обработка информации с диска программой Р-Студио.
После того, как процесс обработки произошел, мы можем наблюдать файлы и папки расположенные в данном разделе диска, в том числе и удаленные. Удаленные папки и файлы помечены красным крестиком.
Для того, чтобы восстановить нужную папку или файл, помечаем его галочкой, и жмем кнопку на панели инструментов «Восстановить помеченные».
После этого, отрывается окно, в котором мы должны указать параметры восстановления. Самым важным является указание директории, куда будет восстановлена папка или файл. После того, как мы выбрали каталог сохранения, и при желании произвели другие настройки, жмем на кнопку «Да».
После этого, файл восстанавливается в ту директорию, которую мы указали ранее.
Нужно отметить, что в демо-версии программы можно за один раз восстановить только один файл, и то размером не более 256 Кб. Если же пользователь приобрел лицензию, то для него становится доступно групповое восстановление файлов и папок неограниченного размера.
Альтернативные Ресурсы & Локализация
Альтернативные Ресурсы и Локализация - серьезная проблема, достаточно хорошо решенная в Андроиде. Обычно чаще всего Вы должны были бы проектировать UI, хорошо подходящий для каждого из возможных разрешений экрана одновременно, что почти невозможно.
Вы можете добавлять в свое приложение различные UI, языки или поддержку устройств с различной конфигурацией харда.
Заметьте, что даже если Вы добавите много разных языков, UI и всех других ресурсов, SDK сам определит набор ресурсов, который будет использоваться. К примеру, Андроид сам догадается, где какой язык Вам нужен и выберет его. Или UI. Чтобы включать дополнительные ресурсы, создайте параллельные папки с ресурсами и к каждому названию через черточку добавьте параметр (спецификатор), куда эта папка относится (язык, ориентация экрана, точки на дюйм, разрешение, …). Вот, например, у этого проекта есть английская и немецкая локализация (здесь только строки):
Андроид поддерживает несколько типов спецификаторов, с различными значениями для каждого. Добавьте их концу названия папки ресурса, отделив от названия черточкой. Вы можете добавить много спецификаторов, отделяя их друг от друга черточками. Например, папка, содержащая drawable ресурсы только для определенной конфигурации:
Более того, Вы можете определить только несколько определенных опций конфигурации, для которых определен ресурс.
Андроид выберет, какой из различных основных файлов ресурса подходит лучше всего во время выполнения, в зависимости от текущей конфигурации устройства.
4 Answers 4
R is a class containing the definitions for all resources of a particular application package. It is in the namespace of the application package.
For example, if you say in your manifest your package name is com.foo.bar , an R class is generated with the symbols of all your resources in com.foo.bar.R .
There are generally two R classes you will deal with
- The framework resources in android.R and
- Your own, in your namespace
It is named R because that stands for Resources, and there is no point in making people type something longer, especially since it is common to end up with fairly long symbol names after it, that can cause a fair amount of line wrapper.
After solving all problems and proceeding with the book, I can add (from the book): This is an auto-generated utility class that provides references to the resources in the project. It is called the "R class" because its name is R.java. It is generated by AAPT from the resourced defined within the res folder.
There is a point making people typing something longer: it's called clean code and might not have reached everyone yet. One letter classes, extensions, variables maybe fine in a local context, but never globally. Ugly names like this lead to redundant questions like this.
What is R: There is nothing very mysterious about R. It is just a class that has many static subclasses, open it up in eclipse and take a look (its under gen/).
Every member of this class is one of two things: 1) static final classes or 2) static final integers which are unique with respect to the other members of their class.
Why is it so cryptic: Its easy to get confused because R is automatically generated by ant. Its cryptic because you aren't supposed to "touch" it manually (of course you can but your changes will be automatically erased upon regeneration). Its additionally cryptic because sometimes eclipse automatically imports androids standard R file (as discussed in the answers above)
Why is it always the first one that cannot be resolved: R follows the rules of Java classes and packages exactly, there is nothing special about how R acts with respect to importation. R will be automatically placed in the package specified by the package entry in your manifest file
To see what package your R file belongs to just open up the gen/ folder in eclipse (packages view). You will see one package listed there, it will have the name you specified in your manifest. Try to delete it, it will come back if all of your resources follow the correct naming rules and all of your xml files follow the correct xml rules and if build automatically is enabled in eclipse.
The key to understanding the R file is to realize that it is in the same package as the other classes even though it is in a different directory then other files belonging to your "main" package. After you understand this and understand the syntax and naming of resource files troubleshooting problems with R is easy.
In android, I'm not sure I quite understand the R class. I'm going through the sudoku example, and I have this snippet of code:
I'm brand new to Java, but from what I gather it looks like it's taking input (the touch screen being touched on the button) and evaluating the argument. Then the case statement is setup if the about button is recognized, and a new interface screen is created and then navigated to on the phone.
If I got the gist of that correct, why is the deal with the "R" class?
Why is it called to recognize the ID of the button?
I thought the super class (in this project) was the SudokuActivity class.
Восстановление по сигнатурам
Если во время просмотра диска вы не нашли нужную вам папку или файл, то это значит, что их структура уже была нарушена, вследствие записи поверх удаленных элементов новых файлов, или произошло аварийное нарушение структуры самого диска. В этом случае, простой просмотр содержимого диска не поможет, и нужно проводит полноценное сканирование по сигнатурам. Для этого, выбираем нужный нам раздел диска, и жмем на кнопку «Сканировать».
После этого, открывается окно, в котором можно задать настройки сканирования. Продвинутые пользователи могут произвести в них изменения, но если вы не очень разбираетесь в подобных вещах, то лучше тут ничего не трогать, так как разработчики выставили по умолчанию оптимальные настройки для большинства случаев. Просто жмем на кнопку «Сканирование».
Запускается процесс сканирования. Он занимает сравнительно долгое время, поэтому придется подождать.
После завершения сканирования, переходим в раздел «Найденные по сигнатурам».
Затем, кликаем на надпись в правом окне программы Р-Студио.
После непродолжительной обработки данных, открывается список найденных файлов. Они сгруппированы в отдельные папки по типу контента (архивы, мультимедиа, графика и т.д.).
В найденных по сигнатурам файлах структура их размещения на жестком диске не сохраняется, как это было в предыдущем способе восстановления, также теряются имена и временные метки. Поэтому, чтобы найти нужный нам элемент, придется просматривать, содержимое всех файлов аналогичного расширения, пока не отыщем требуемый. Для этого достаточно просто кликнуть правой кнопкой мыши по файлу, как в обычном файловом менеджере. После этого, откроется просмотрщик для данного типа файлов, установленный в системе по умолчанию.
Восстанавливаем данные, как и в предыдущий раз: отмечаем нужный файл или папку галочкой, и жмем на кнопку «Восстановить помеченные» в панели инструментов.
Как пользоваться R-Studio
Содержание: Как пользоваться R-Studio
3 Answers 3
R.java is the dynamically generated class, created during build process to dynamically identify all assets (from strings to android widgets to layouts), for usage in java classes in Android app. Note this R.java is Android specific (though you may be able to duplicate it for other platforms, its very convenient), so it doesn't have much to do with Java language constructs. Take a look here, for more details.
R is a class that contains ONLY public constants. (public static final).
It is a generated class (by Android Plugin in Eclipse) that reflects the various values you defined in the res file.
For instance, you should have something like:
somewhere in one of your layout/menu xml file in the project, and once you wrote that, Eclipse will generate a constant in the R file (which you can find it under gen/PACKAGE/R.java )
Read the Resource guide in Android Developers for more information about this.
R class is generated by Android tools from your resources before compiling your code. It contains assigned numeric constant for each resource that you can refer in your project. For example, you have XML resource file that contains about_button . If you didn't have R class, you would have to use a string "about_button" to refer to it in code. If you make a mistake in this string, you will only learn about it when you run your application. With R you will see the error much earlier at compile time.
R is structured in such a way that you can refer to resources via its inner classes. For example, R.id contains id constants and R.layout contains layout constants.
Редактирование дисковых данных
О том, что программа R-Studio не просто приложение для восстановления данных, а многофункциональный комбайн для работы с дисками, свидетельствует то, что у него имеется инструмент для редактирования дисковой информации, которым является шестнадцатеричный редактор. С его помощью можно редактировать свойства NTFS файлов.
Для этого, следует кликнуть левой кнопкой мыши по файлу, который хотите отредактировать, и в контекстном меню выбрать пункт «Вьювер-Редактор». Либо, можно просто набрать комбинацию клавиш Ctrl+E.
После этого, открывается редактор. Но, нужно отметить, что работать в нем могут только профессионалы, и очень хорошо подготовленные пользователи. Обычный пользователь может нанести серьезный вред файлу, неумело используя данный инструмент.
Волшебный R.java
R.java проекта - автоматически сгенерированный файл, индексирующий все ресурсы Вашего проекта. Вы используете этот класс в своем исходном тексте как своего рода способ обратиться к ресурсам, которые Вы включили в свой проект. Это особенно важно, учитывая особенности интегрированных сред разработки, потому что позволяет Вам быстро и в интерактивном режиме определять местонахождение определенной информации, которую Вы ищете. Дополнительно во время компиляции Вы получаете уверенность, что ресурс, который Вы хотите использовать, действительно существует.
Ни один пользователь не застрахован от потери данных с компьютера, или с внешнего накопителя. Произойти это может в случае поломки диска, вирусной атаки, резкого обрыва электропитания, ошибочного удаления важных данных, минуя корзину, или из корзины. Полбеды, если удалена информация развлекательного характера, но если на носителях находились ценные данные? Для восстановления потерянной информации существуют специальные утилиты. Одна из лучших из них называется R-Studio. Давайте подробнее поговорим о том, как пользоваться Р-Студио.
Создание образа диска
Кроме того, программа R-Studio позволяет создавать образы всего физического диска, его разделов и отдельных директорий. Данную процедуру можно использовать, как в качестве резервного копирования, так и для последующих манипуляций с дисковым содержимым, без риска потери информации.
Для инициирования данного процесса, кликаем левой кнопкой мыши по нужному нам объекту (физическому диску, разделу диска или папке), и в появившемся контекстном меню переходим в пункт «Создать образ».
После этого, открывается окно, где пользователь может произвести настройки создания образа под себя, в частности указать директорию размещения создаваемого образа. Лучше всего, если это будет съемный носитель. Можно также оставить значения по умолчанию. Чтобы непосредственно запустить процесс создания образа, жмем на кнопку «Да».
После этого, начинается процедура создания образа.
Как видим, программа R-Studio – это не просто обычное приложения для восстановления файлов. В его функционале имеется ещё много других возможностей. На подробном алгоритме выполнения некоторых действий, доступных в программе, мы остановились в этом обзоре. Данная инструкция по работе в R-Studio, несомненно, будет полезна, как абсолютным новичкам, так и пользователям с определенным опытом.
Ссылка на Ресурсы
Значение в атрибуте или ресурсе может также быть ссылкой на другой ресурс. Это часто используется в layout файлах, чтобы хранить строки (таким образом можно локализовать приложение) и изображения (находящиеся в другом файле), хотя ссылка может быть на любой тип ресурса, включая цвета и числа.
Например, если у нас есть ресурсы с цветами, мы можем написать layout файл, который установит цвет текста на значение, содержащееся в одном из ресурсов:
Обратите внимание на префикс "@", показывающий, что это - ссылка на ресурс, текст после него - название ресурса в форме @[пакет:]тип/имя. В примере мы не определяем пакет, потому что ссылаемся на ресурс в нашем собственном пакете. Чтобы сослаться на системный ресурс, Вы должны были бы написать:
В следующем примере, мы используем ссылку на ресурс, храня строки в layout файле так, чтобы они могли быть локализованы:
Читайте также:
- Кабель usb тип а с фикс usb тип b 2м caualb 2m 822335077379 l com
- Почему торренты медленно качаются через usb модем
- Apache не хватает памяти
- Что способствует мобильной связи между людьми с помощью компьютера и хранить пересылаемую информацию
- Для управления групповой политикой необходимо войти в компьютер под учетной записью домена