Selectors in android xml

Android ImageButton selector example

By mkyong | Last updated: August 29, 2012

Viewed: 287,123 (+122 pv/w)

In last Android tutorial, you use “ ImageButton ” to display a “ Button ” with a customized background image easily. However, you can do more than that just a simple image, Android allow you to change the button’s image depends on different states like button is focused or button is pressed.

This example is referenced from this Android custom button article, with minor changes.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Add Images to Resources

Prepare 3 images for button states, and put it into “resource/drawable” folder.

  1. button_normal_green.png – Default image button.
  2. button_focused_orange.png – Display when button is focused, for example, when phone’s keypad is move (focus) on this button.
  3. button_pressed_yellow.png – Display when button is pressed.

2. Add Selector for different button states

Now, create a new XML file in “res/drawable/” folder, in whatever name you want, in this case, we just give a name as “ new_button.xml “. This file defined which button state is belong to which image.

Now, you can refer to this button via this Id : @drawable/new_button .

3. Add Button

Open “res/layout/main.xml” file, add a normal button, and attach the background image to above “new_button” via “ android:background=»@drawable/new_button ”

4. Code Code

A normal button with a simple click listener.

5. Demo

Run the application.

1. Result, default button. (button_normal_green.png)

2. Button is focused. (button_focused_orange.png)

3. Button is pressed. (button_pressed_yellow.png)

Download Source Code

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

This tutorial still can be use. AWESOME !!

Thanks for explaining this so well, It really helps me in understanding basic android concepts of xml.

Thanks for sharing this is Really helped me, ur explanation is very clear and u added the downloadable file thats add the advantage to rectify errors more accurately рџ™‚ Good Work Keep Going

Nice, but I have a question about it.
I would like to have a kind of state on this image button.

I now have a toggle button like this.

private OnClickListener powerButtonListener = new OnClickListener() <
public void onClick(View arg0) <
ToggleButton powerButton = (ToggleButton) arg0;
if (D) Log.d(TAG, “powerButtonListener” + powerButton.isChecked());
searchAndConnect();
if (powerButton.isChecked()) <
powerOn = 1;
sendColorToArm();
> else <
powerOn = 0;
sendColorToArm();
if (mBTSerialService != null) mBTSerialService.stop();
>
>
>;

(My image’s are in a xml file called on_btnaction.xml)

in mainActivity.java.
public class mainActivity extends Activity <
ImageButton on_btnaction;

@Override
public void onCreate(Bundle savedInstanceState) <
on_btnaction = (ImageButton) findViewById(R.id.on_btnaction);
on_btnaction.setOnClickListener(on_btnactionListener);
>

private OnClickListener on_btnactionListener = new OnClickListener() <
public void onClick(View arg0) <
ImageButton on_btnaction = (ImageButton) arg0;
if (D) Log.d(TAG, “on_btnactionListener” + on_btnaction.getDrawableState());
searchAndConnect();
if (on_btnaction.getDrawableState(1)) <
powerOn = 1;
sendColorToArm();
> else <
powerOn = 0;
sendColorToArm();
if (mBTSerialService != null) mBTSerialService.stop();
>
>
>;

Читайте также:  How to add certificate to android

Well, what do you think and what do I have to do to make the ImageButon like the ToggleButton?
Thanks in advance.

Источник

artzmb / layout#activity_main.xml

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

xml version = » 1.0 » encoding = » utf-8 » ?>
RelativeLayout
xmlns : android = » http://schemas.android.com/apk/res/android «
xmlns : app = » http://schemas.android.com/apk/res-auto «
xmlns : tools = » http://schemas.android.com/tools «
android : layout_width = » match_parent «
android : layout_height = » match_parent «
tools : context = » ru.artzmb.solar.MainActivity » >
ImageView
android : layout_width = » 100dp «
android : layout_height = » 100dp «
android : layout_centerInParent = » true «
android : clickable = » true «
app : srcCompat = » @drawable/solar «
tools : ignore = » ContentDescription «
/>
RelativeLayout >

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

xml version = » 1.0 » encoding = » utf-8 » ?>
selector xmlns : android = » http://schemas.android.com/apk/res/android » >
item android : color = » @color/red_800 » android : state_selected = » true »/>
item android : color = » @color/red_800 » android : state_pressed = » true »/>
item android : color = » @color/red »/>
selector >

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

xml version = » 1.0 » encoding = » utf-8 » ?>
vector xmlns : android = » http://schemas.android.com/apk/res/android «
android : width = » 100dp «
android : height = » 100dp «
android : viewportWidth = » 100 «
android : viewportHeight = » 100 «
android : tint = » @color/solar » >
path
android : fillColor = » #ffffff «
android : pathData = » M35.48 0L50 14.52 64.52 0v32.26L50 46.77 35.48 32.26zM100 35.48L85.48 50 100 64.52H67.74L53.23 50l14.51-14.52zM64.52 100L50 85.48 35.48 100V67.74L50 53.23l14.52 14.51zM0 64.52L14.52 50 0 35.48h32.26L46.77 50 32.26 64.52z »/>
vector >

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

xml version = » 1.0 » encoding = » utf-8 » ?>
resources >
color name = » red » >#f44336 color >
color name = » red_800 » >#c62828 color >
resources >

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Использование селектора для изменения цвета текста TextView

Я пытаюсь использовать TextView для определения стиля TabWidget на tabhost.

Я просто создал селектор для bgcolor и отлично работает, но я хочу сделать селектор для textColor, но цвет текста не изменяется:

Это мой tab_text_selector.xml:

И это код, когда я пытаюсь использовать в textView:

Я знаю, что цвет текста должен быть белым в любом случае, но это не так.

Вы должны использовать getColorStateList () . И для xml, см. Здесь

Я также боролся с этой проблемой, если вы хотите использовать state list , вам нужно объявить его в папке с color ресурсами вместо drawable папки и использовать setTextColor(getResources().getColorStateList(R.color.tab_text_selector)) .

Читайте также:  Samsung android при hard reset

1) Используйте tab_text_selector.xml, как показано ниже, и поместите его в папку res / color:

И установите его в текст, как показано ниже.

2) Второй вариант: если вы используете textview в xml вместо использования программной программы, используйте tab_text_selector.xml, как показано ниже:

Используйте этот способ:

Но лучше поместить цвет в /res/color/yourcolor.xml

Просто сделайте Selector для textcolor

Затем установите для свойства textColor Textview значение clickable = true

@ Ffleandro, @ ρяσѕρєя K отвечает на лучший вариант, я думаю, используя лучший выбор ColorStateList для более старых и последних версий Android.

Вы использовали белый цвет во всех случаях фокус, выбранный и нажатый.

Пожалуйста, используйте и протестируйте с другим цветом.

Также необходимо использовать случай по умолчанию с определенным цветом, например black, вместе со всем случаем .. когда не используется состояние по умолчанию.

Источник

Selectors in android xml

Create a selectors in android

In Android GUI is always an important part of any application, because ordinary users don’t know and don’t care about what’s behind the scene; they want something easy to work with and now a days attractive GUI is a must for most applications.

Although making an appealing and innovative interface needs something more than just programming skills and knowledge, every programmer should know how to customize different GUI components within whatever framework and environment they are working.When designing GUIs, most of the times you want to change the appearance of buttons, input Fields, menus etc..

Android Selectors have been provided to solve all these kind of problems, they enable us to decide what to show and how to show based on different states of each components. For example. You can tell a button to have black background color with red text color when it is in pressed state or whatever else.

Copyright 2013, Grishma Dixit

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

We’d love for you to participate in the development of our project. Before we can accept your pull request, please sign our Individual Contributor License Agreement. It’s a short form that covers our bases and makes sure you’re eligible to contribute. Thank you!

Источник

Parsing XML data in Android Apps

Jun 28, 2018 · 4 min read

JSON is become a very widespread format for the Web Services but in some cases, you would have to parse data in the good old XML format. In that tutorial, you are going to learn how to parse a XML file on Android.

Note that there are various XML parses available in the Android SDK in standard. Thus, you can use the following solutions :

  • XMLPullParser API
  • DOM Parser API
  • SAX Parser API

As usual, each parser has its advantages and drawbacks.

The recommendation on Andr o id is to use the XMLPullParser API which consumes less memory than the DOM Parser API which loads the complete XML file in memory before parsing it.

So, in this tutorial, we will use the XMLPullParser API. Note that you can also discover this tutorial in video on YouTube :

Читайте также:  Настройки apn ростелеком андроид

Creating a simple User Interface

To display the parsed XML data, we need to create a simple User Interface. It will consist in a simple TextView centered on the screen :

Defining XML data to parse

Then, we define some XML data to parse inside a file under the assets directory of our Android project. This file will be named data.xml and will contain some NBA players with data like name, age and position played :

Creating a Player POJO

To map the data for each player, we create a Player POJO (Plain Old Java Object) :

Preparing the XML Parser

The first step is to load the XML file from the assets of our Android Application. For that, we define a parseXML method. We create a new instance of the XMLPullParserFactory class. Then, we create a new XMLPullParser instance by calling the newPullParser method of the XMLPullParserFactory got previously.

We got an InputStream on the XML file by calling the open method of the AssetManager instance. With that instance, we can set the input on the XMLPullParser instance. It gives us the following code :

Parsing the XML data

Now, we need to parse the XML data. The parsing will be processed in the processParsing method. We start by getting the current event type from the parser by calling the getEventType method.

Then, we enter in a loop while the event type is different of the XmlPullParser.END_DOCUMENT constant. In the loop, when we meet a XmlPullParser.START_TAG event type, we get the name of the current tag by calling the getName method.

When we have a player tag, we create a new Player instance and we add it in an ArrayList of Player. This list will be used to store all the players read from the XML file.

If the current player is not null, we are reading data for a player. We have to check if the tag is name, age or position. For each case, we call the nextText method of the parser to get the value associated to the tag. Then, we set the value on the current player.

At the end of the loop, we have stored all the players from the XML file on the ArrayList of Player. Note that just before the end of the loop, you need to call the next method of the parser to pass to the following event.

It gives us the following code :

Displaying the XML data

The last step is also the simplest. We need to display the players in our TextView via the printPlayers called at the end of the processParsing method.

In that method, we iterate on the ArrayList of Player and for each player we add its properties (name, age and position) on a StringBuilder instance. Finally, we display the text on the TextView by calling its setText method with the value of the StringBuilder instance.

It gives us the following complete code for the MainActivity :

Our App in Action

Best part of the tutorial is coming since it’s time to put our App in Action. When, you will launch the Application, you should have the following result :

That’s all for that tutorial.

To discover more tutorials on Android development, don’t hesitate to subscribe to the SSaurel’s Channel on YouTube :

Источник

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