Xml in android programming

Programming VIP

Very Interesting Programming

Namespaces for XML in Android

Introduction to basic concepts

Namespace

XML namespaces provide a way to avoid element naming conflicts.

For example, there is a student named Lin Xiaoming in School A and a student named Lin Xiaoming in School B. How can we identify these two students with the same name? Namespace will come in handy at this time. A and B can then be considered namespaces. In other words, the namespace contains a collection of specific attributes.

Common Namespaces in Android

The following sections introduce android, tools, and app (custom namespaces), which are common namespaces.

1,android

xmlns:android=»http://schemas.android.com/apk/res/android»
In the Android layout file, we all have to define such a namespace on the root element. Next, we will explain this line of code one by one.
xmlns: xml namespace, declaring that we are going to start defining a namespace
The string in which android is located, which we call namespace-prefix, actually means giving the namespace a name.
http://schemas.android.com/apk/res/android This looks like a URL, but this address is not accessible. In fact, this is a URI (Unified Resource Identifier), so its value is fixed, equivalent to a constant.

With him, you will be prompted to enter something, which can also be understood as a grammar file.

So what does this line of code do? The attributes in the namespace that we write in the code for the root element can be referenced, such as:

In this layout, as long as the attribute begins with android: it refers to the attribute in the namespace. As mentioned above, Android gives the namespace a name, just like we usually define variables, so the name can also be taken as our favorite. For example, if I take it as myns, then the code above We can also write as follows:

2,tools

Next, I will introduce three ways to use tools, which are also his characteristics.

2.1. tools only works at the development stage

We can think of him as a tool namespace, a tool to help developers. It only works at the development stage. When an app is packaged, all tools attributes will be discarded!

For example, basically in the android namespace, we want to test the effect of a component on the screen at the coding stage, and when app is installed on the phone, discard this code, then we can replace android with tools namespace:

This is the layout in the layout. When we switch to the view window (Design), we see that the top of the label is centered.

Then, when we run it on our mobile phone, it’s like this:

As shown above, tools:layoutgravity= «center» is indeed abandoned behind the runtime!

2.2. Viewing Activity Layout Effect in tools:context Development

The use of context is followed by the full package name of an Activty. What does it do?

When we set an Activity theme, it is set in AndroidManifest.xml, and the effect of the theme can only be displayed in Activty after running. With the help of context attribute, we can see the effect of the theme set in Activity in the layout in the development stage.
tools:context=»com.littlehan.myapplication.MainActivity»
By adding this line of code to the layout, you can see the effect of binding the theme to MainActivity in the design view.

2.3. Viewing fragment layout effect in tools:layout development

When we load a fragment on Activity, we need to see the effect after loading after running. Is there a way to display it in the layout preview window during the testing phase? The answer is yes, with the help of the layout attribute, for example,
Add such a line of code to the layout:
tools:layout=@layout/yourfragmentlayoutname
In this way, your fragment layout will be previewed on the specified main layout.

3. Customizing Namespaces

If you use DataBinding, you will use the app attribute in xml, which is actually a custom namespace.

Some friends may ask, where is the reflection of self-definition?

In fact, it can also be written as follows:
xmlns:app=»http://schemas.android.com/apk/res/ Complete package name»
Just fill in our package name after res/ However, in my own Android Studio 2.0, this is not recommended, so it is more recommended that you use the first naming method.

Usually custom namespaces are inseparable from custom views. When Android’s own controls can’t meet our needs, we will draw some views ourselves. When we add custom attributes to these customized views, we need to create our own namespaces.

As I said at the beginning, the namespace contains a collection of specific attributes, so the idea is clear, that is to say, the actual process of customizing a namespace is to customize attributes.

We learn about custom namespaces through a simple custom TextView. The process of customizing the View can be divided into the following steps:

Inheriting View Class

Create a class named CustomTextView Inheritance View
(View is the parent class of all views) and implements its three constructions

Drawing Views

Overload the onDraw() method to draw a paragraph of text

Use custom layout

Introducing custom controls into layout

Here, a custom control is introduced into the layout, and we can switch to the view window to see the effect.

But this custom control can not change the font color, font size, custom text and so on in xml. The implementation of this function is actually the process of creating custom attributes in XML and parsing attributes in custom View s.

Читайте также:  Как сделать свою бутанимацию для андроид

Custom Properties

Create a new xml file named attrs under the values root directory to customize our attributes (the attributes defined here are the attributes in our custom namespace)

Name defines the name of an attribute
format defines the type of attribute

Parsing attributes

Resolve these attributes in CustomeTextView

Use custom properties

To use custom attributes, you need to customize the attribute namespace by inserting such a line of code under the root element of the layout file:
xmlns:app=»http://schemas.android.com/apk/res-auto»

So we can use custom attributes:

Switch to the view preview window and you can see that the custom properties are in effect:

summary

In Android, namespaces can be divided into three categories:

Among them, the attributes in 1 and 2 namespaces are encapsulated by the system, and the attributes in the third namespace are user-defined.

Added by vijayfreaks on Thu, 18 Jul 2019 04:11:20 +0300

Источник

Learning to Parse XML Data in Your Android App

Introduction

We are in an age where, typically, an application cannot work in total isolation and does not have all the data it needs to do its work. It generally has to communicate to some other application–maybe over the internet–and read or send some data to it.

However, the applications with which your app communicates might not be developed using the same technology as yours. For smooth data exchanges between your app and some other application you might be exchanging data in an open format like Extensible Markup language or XML.

An XML document is a human readable text document that contains some starting and ending tags with attributes and data in those tags. Most of the languages and platforms have support for parsing and creating XML documents in them. Android also provides us APIs so that we can work and process XML documents in our app with ease and flexibility. In this article, we are going to see how you can work effectively with XML documents in your Android app.

The classes for XML parsing in Android

There are various XML parsers we can use on the Android platform. For XML, Android recommends the use of the XMLPullParser . Android gives a multiple implementation of the XMLPullParser and you can use any of them in your program. Depending on the way you create your XMLPullParser , the implementation of the parser will be chosen.

Instantiating your parser

As stated above, there are multiple ways in Android you can create an XMLPullParser . The first way to do it is using the Xml class as shown below:

You have to just call newPullParser which will return you a reference to the XMLPull parser. Or you can get a reference from the XmlPullParserFactory as shown below.

Parsing the XML

Once we have the parser reference it’s now time to use it to parse an XML. We are going to use the following XML as the XML to parse. So now create a file called temp.xml in your assets folder with the content:

The code of the activity to read and parse is as follows:

In the above code we have created a small class called Product which has three members: name, quantity and color.

In the activity we first get the XMLPullParser instance then we open the temp.xml as an inputstream . Once that is done we set the inputstream as input to the parser. Then we parse the xml in our function parseXML .

In the function parseXML we create an ArrayList in which we will store all the products which we will parse from the XML. Once that is done we create a loop which will work till the end of the document is reached.

At the start of the document we created the ArrayList of products. If a tag starts and if the tag is product we know that now it’s a new product so we create a new product instance. Then if the other tags are read we will just read and add the values in our Product instance.

Once the Product tag is ended we add the product to the ArrayList . Once all the products are added we call the function printProducts in which we iterate over the ArrayList and then print the values on the screen.

If we run the activity now we will see the output as follows:

Other Parsers used for XML

There are other parsers also that can be used to parse XML in Android. The DOM parser can be used which creates a complete memory model of the XML and can be used to either create or parse XML. DOM parsers generally consume a lot of memory.

You can get the instance of a DOMBuilder as shown below

SAX Parsers

The SAXParsers can also be used to parse XML and consume much lesser memory then DOM parsers. The SAXParsers can be used only to parse XMLs not to create them. You can get the reference of a SAXParser as shown below:

Conclusion

XML documents are becoming a standard way to exchange data between applications over the internet. With our Android apps becoming smarter and smarter it might be necessary for your Android app to communicate and exchange data between different applications over the internet. Android provides a rich set of APIs to work with XML documents in your Android app.

With the help of these APIs you can easily incorporate XML into your Android app. The XML parsers do the tedious work of parsing the XML and we have to just write the code to fetch the appropriate information from it and store it for further processing.

So, have fun processing XML in your next Android app.

And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Beginning Android Development.

Comments on this article are closed. Have a question about developing Apps? Why not ask it on our forums?

Источник

Читайте также:  Телефоны за 4000 сенсорные андроид

Работа с XML в Android

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

Библиотеки Android имеют набор классов для работы с XML-документами с произвольной структурой и содержанием.

Шаг 1.

Для того чтобы упаковать статический XML файл вместе с вашим приложением, вам нужно поместить его в папку: res/xml/

В каталоге res/ создайте подкаталог xml/ в котором будет располагаться наш ХМL-файл.

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

Шаг 2.

Рассмотрим загрузку XML-документа произвольной структуры из ресурсов в код программы.

Создадим приложения, которое будет уметь способность читать список имен, фамилий и телефонов, определенных в XML-файле.

Теперь создадим XML файл который будет хранить Имена, Фамилии и номера телефонов сотрудников фирмы и сохраним его в res/xml/ под именем contacts.xml.

Вот как будут выглядеть XML файл contacts.xml

Шаг 3.

Создадим View состоять она будет с LinearLayout и ListView и назовем main.xml:

Шаг 4.

Загружаем файл contacts.xml, созданный ранее:

Метод getXml() возвращает XmlPullParser, используя который можно прочитать загруженный XML-документ в цикле while:

В конечном итоге ваше приложение должно выглядеть так:

Весь код MyActivity:

Обратите внимание что наследуется MyActivity не от Activity а от ListActivity.

Источник

An introduction to XML for new Android developers – the powerful markup language

If you’re interested in Android development, chances are you’re going to need to learn some programming.

In most cases, that will mean learning Java or Kotlin, either of which is officially supported by Android Studio, the official “IDE” for Android Development from Google. However, no one ever talks about XML, and this can lead to confusion when you open up a new project for the first time and notice that there are actually two different main files and two different types of script. Hence this article, which will serve as your introduction to XML for Android development.

Unless you’re making a game using Unity or Unreal, chances are you’re also going to need to understand this “markup language” to define your layout. If you try and skip it, eventually you’ll hit a road block.

Read on then to discover what XML is, why you need it, and how to get started.

A basic introduction to XML and markup languages

XML stands for Extensible Markup Language, which gives us a clue to what it does.

A markup language is slightly different from a programming language. Whereas a programming language (C#, C++, Java, Kotlin, Python, BASIC) will allow you to define behaviors, interactions, and conditions; a markup language is used more to describe data, and in this case, layouts. Programming languages create dynamic interactions, whereas markup languages generally handle things like static user interfaces.

  • Markup languages control presentation data.
  • Scripting languages mediate between programs to generate data.
  • Programming languages transform data.

Despite appearances, XML is not a programming language.

Another example of a markup language is HTML, which defines the appearance of a website. HTML places the images and text on a website and sets the font and color. You couldn’t make a computer game in HTML (not a very good one anyway), which is why you might turn to something like JavaScript for more interactive elements. Though just to complicate matters, JavaScript is technically a scripting language!

In fact, XML was originally introduced by the World Wide Web Consortium (W3C) to deal with the inherent limitations of HTML. Specifically, HTML is not terribly readable for a computer, because it doesn’t explain what anything on the page actually is.

Mrs. Mary McGoon

1401 Main Street

Anytown, NC 34829

Here, you and I know the information is an address, but all the browser or computer knows is where to start new lines. That’s where something like XML comes in handy.

Here’s how the same information might look in XML:

XML is used anywhere that can benefit from adding context to data. It is used across the web to make search smarter and simplify data exchange. XML is actually based on the Standard Generalized Markup Language (SGML), which has been used by the publishing industry for decades.

XML performs the same function in Android app development: describing data and introducing elements.

Specifically, XML sets the layout of things like buttons and images, and defines the font, color, and any text that shows by default. To make those buttons actually do anything, you will need to use a programming language like Java or Kotlin, though.

XML in Android development

When you create a new project in Android Studio, you will be greeted by a hierarchy of different files and folders, which can be a little daunting for complete beginners. It’s a rather jarring introduction to XML, no doubt!

You just need to concentrate on two files for now: MainActivity.java and activity_main.xml.

To make life just a little simpler, Android Studio normally opens both these files as soon as it boots up.

You’ll also notice that both these files have a little bit of code already in them. This is called “boilerplate code,” which is code that almost every program needs, and so which Android Studio will populate for you in order to save time.

One line in MainActivity.java reads:

setContentView(R.layout.acivivty_main)

This means the activity this Java code controls will display the activity_main.xml file, and you may reference certain elements from that as you go.

You can assign any XML file to any Java file with this, and you can create as many of both as you like. However, by default MainActivity.java will always be the class (java file) Android loads first when running your programs.

Using XML in your Android app

To recap, XML describes the views in your activities, and Java tells them how to behave. To make changes to the layout of your app then, you have two main options.

The first is to use the Design view. Open up the activity_main.xml file in Android Studio and get your first introduction to XML. You’ll notice there are two tabs at the bottom of that window: Design and Text. The Text view will show you the actual XML code, but the Design view will let you manually edit the layout by dragging and dropping elements into the render of your activity.

Читайте также:  Learn to fly для android

XML files can also help store strings. Using the Design view is easier for beginners, though it can lead to complications. For one, you will run into the limitations of XML early on when the designer refuses to let you drop items into specific places. Without the knowledge of why, this can make designing your app an exercise in frustration!

At the same time, having a better understanding of XML will also help when it comes to handling the code. Otherwise you might find yourself stumped when it comes to things like finding the ID of the view, or remembering what type of view it is you’re working with.

It is also possible to “instantiate” views at runtime from within your code, but this can be tricky to juggle if you’re creating a complex UX.

XML outside of layout files

Sometimes XML will be used to describe types of data other than views in your apps; acting as a kind of index that your code can refer to. This is how most apps will define their color palettes for instance, meaning that there’s just one file you need to edit if you want to change the look of your entire app.

You can find this information in the colors.xml file, located in app > resources > values > colors.xml, which contains tags that assign different names to various color codes:

#008577

You can then refer to this tag subsequently in your Java code or your XML code to refer to that particular hue.

Another alternative use of XML is in the Android Manifest (AndroidManifest.xml). This holds a lot of data describing your app, like the label (the app’s name), the icon, and instructions about which activities to load first. This helps launchers display the app correctly on the homescreen, and it’s also used by app stores.

Getting started with XML code for Android

Most of the time you’ll use XML to define your layouts. While we won’t go too in depth in this introduction to XML for Android, let’s go over some basics to help you get started.

Syntax

Apart from being another markup language, something else XML has in common with HTML is its use of tags.

XML mainly uses tags to introduce elements into a layout, whether they’re Views or ViewGroups. A view is basically any of the widgets that make up a typical utility app. Examples include images (ImageViews), text (TextView), editable text boxes (EditText), web pages (WebViews), and buttons (err, Button).

You’ll start by using angle brackets to open the section, then you’ll introduce the view, and then you’ll set all the parameters. Some of these parameters will be compulsory, while others will be optional.

Managing views and viewgroups

As you may already have guessed, a ViewGroup is a group of these views. These are also referred to as layouts, and serve as hierarchical arrangements of views. A linear layout for example places all its children in a linear vertical or horizontal arrangement. Meanwhile, a ConstraintLayout will allow you to define the positions of views by their relationship with other views in the layout and the boundaries of the activity. This way, the views can maintain their relative positions, even as the dimensions of the device vary.

Some Views can also be ViewGroups, such as the RecyclerView, which arranges other views in a scrolling list.

If you open up your activity_main.xml file right at the start for instance, you’ll see it is already populated with some code. This is a simple TextView that shows the words “Hello World” as is traditional. If we look at this, it can give us some insight into how XML is used:

So basically, it starts out by opening a constraint layout and telling it to “match_parent” meaning it will fill the exact same size as the parent layout. In this case, there is no parent and so the activity itself becomes the default. All parameters are set before the closing angle bracket.

Next, it introduces the EditText and sets parameters such as the width, height, text to show, ID, and position. The ID is what we will use to refer to this EditText subsequently in our Java code, should we wish to change what it shows. Because we are using a ConstraintLayout, we need to control the layout by anchoring it to something else.

Let’s use the top, bottom, and sides of the “parent,” which is the ConstraintLayout. The View is now being pulled between those four points and will therefore sit comfortably at the point in the middle. If you switch to the Design view, you can see this in action, denoted by small white arrows.

Notice that we end this section with an ending tag: a forward slash, followed by the name, and the closing angle bracket. That tells Android we’ve finished talking about the EditText.

After that, we also need to create a closing tag to close off the ConstraintLayout ViewGroup. We could now introduce a new type of layout, or we could use nested layouts by adding a new ViewGroup tag inside the ConstraintLayout tags.

Closing comments

In reality, XML is actually supremely simple and follows only a few set rules. The main complication is learning all of the different views and all of the different properties each needs defined. Fortunately, you can find a lot of this information online, or simply use the design view to experiment and see how the code should look.

You might be bashing your head against the wall right now thinking that there is “yet another thing to learn,” but once you get the hang of it, it will actually make your life much simpler.

It might not “technically” be a programming language, but many people will describe it as such anyway. So now that you’ve read our introduction to XML, you can claim to actually know two new languages!

Источник

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