Android Real-CardView selector and Grideview item pressed state reserved Selector (state_activated) implementation

Source: Internet
Author: User



Android Selector is more familiar to Android developers, as long as you define a selector XML file in a drawable directory, Using this XML in a layout file background referencing the XML file or setbackgrounddrawable it in the code allows for the effect of different States, such as the control being pressed or focused or activated. Do you really know all about the use of selector?


Objective


The project does use a number of labels, and then check the specification to add color to the text border, for the length and number of uncertain situations we can usually in the code through the length of the dynamic new control and then give them a click event, and set the background for each control is achievable, But the use of Grideview words is still not good to achieve, so it was searched the next found state_activated can be perfect to achieve this function.


The effect is as follows


Android 4.4 Effect:






Android 5.1 effect





Selector Property Introduction


The root node of the selector must be item, which can contain one or more item elements
Xmlns:android String, required, namespace defining XML, must be "http://schemas.android.com/apk/res/android"


Android:state_pressed
Boolean, "True" indicates the use of a pressed state (e.g. button press), "false" for non-pressed state

Android:state_focused
Boolean, "True" means the focus state is used (for example, with a focus button); "False" indicates a non-focused state using

android:state_selected
Boolean, "True" means the selected state is used (for example, tab-Open); "false" indicates unchecked state use

Android:state_enabled setting whether to respond to an event, refers to all events


Haha, the above properties you often use, because our needs are generally have no focus on whether or not to change the text and background color of the picture, then, such as the ListView and Grideview after the click State retention you may not necessarily use.


Android:state_checkable
Boolean, "True" indicates that the status can be checked, "false" indicates non-tick status, (useful only for switches that can be checked-non-tick components)

Android:state_hovered
This is api14 above, this is when the cursor moved to a component on the state of the time, so far, have not seen which mobile phone device with a mouse and other things, perhaps this is specifically for the tablet set or may appear with a mouse and other devices and prepared it, the document says, This value is generally set to the same value as focused.

Android:state_window_focused
This is whether the current interface is the focus of the two state settings, so we are generally not used to

android:state_activated
Indicates the state of the current control being activated, which may not be used by many Android developers, and it retains the pressed state.


Please see the official API for details, which are written in more detail http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList


Examples of selector use


The function of general selector is to set the background foreground for the view control, and so on, because selector's intention is to change different pictures for the same graph depending on the state. Then use statelistdrawable to replace the ordinary drawable, the specific drawable of the drawing you can refer to the various drawable of Android, so drawable can be color,shape,img, The point today is not to draw drawable but to use selector.


Set selector for CardView (state_pressed use)


I believe a lot of people have used CardView, and now we're adding a perspective to it selector


<android.support.v7.widget.CardView
         xmlns: app = "http://schemas.android.com/apk/res-auto"
         android: layout_width = "match_parent"
         android: layout_height = "wrap_content"
         android: layout_margin = "8dp"
         android: foreground = "@ drawable / card_foreground"
         android: id = "@ + id / cv_item"
         android: elevation = "2dp"
         app: cardCornerRadius = "4dp"
         app: cardBackgroundColor = "@ android: color / white"
         app: cardPreventCornerOverlap = "false"
         app: cardUseCompatPadding = "true"
         android: clickable = "true">

         <TextView
             android: id = "@ + id / text_view"
             android: padding = "20dp"
             android: layout_width = "match_parent"
             android: layout_height = "wrap_content"
             android: gravity = "center"
             android: text = "selector press and release effect" />
     </android.support.v7.widget.CardView>


To set the selector premise, we have to prepare drawable, and then cardview we set selector it to distinguish between 5.0 before and after the effect, we all know that after 5.0 click will have water ripple effect (ripple), and then we did not have this effect.


And then how do we go about setting it up:

drawable file Adaptation


Card_foreground.xml



 
 
 
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#e0F5AD6E"/>
            <corners android:radius="@dimen/card_radius" />
        </shape>
    </item>
    <item android:state_focused="true" android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="#0f000000"/>
            <corners android:radius="@dimen/card_radius" />
        </shape>
    </item>
</selector>


Card_foreground_selector.xml


 
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#F5AD6E"
    android:drawable="@drawable/card_foreground_selector" />
DRAWABLE-V21 file Adaptation


Card_foreground.xml



 
 
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#F5AD6E"/>
        </shape>
    </item>
    <item android:state_focused="true" android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="#0f000000"/>
        </shape>
    </item>
</selector>


Card_foreground_selector.xml


 
 
 
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#F5AD6E"
    android:drawable="@drawable/card_foreground_selector" />


What ripple and inset is not the focus, the focus is how we write selector file, in fact, it is particularly simple, you have how many states with item separate good, and then for various states configuration drawable good, Here I use shape directly as a drawable.


Grideview Item pressed status reserved (state_activated)


In fact, I did not encounter this situation when I did not pay attention to the use of state_activated, haha, indeed to the development brought great convenience.
When we find that the state_selected in selector does not work: Note the state_activated state, the function is to activate the view after the state until the reservation, unless the activation state is canceled, so you must specify the Android:state_ Activated is true or false.
Gride_selector.xml


<? xml version = "1.0" encoding = "utf-8"?>
<selector xmlns: android = "http://schemas.android.com/apk/res/android">

    <item android: state_activated = "false">
        <shape xmlns: android = "http://schemas.android.com/apk/res/android">

            <!-Line width, color gray->
            <stroke android: width = "1dp" android: color = "# A3A3A3"> </ stroke>
            <!-Rectangle Fillet Radius->
            <corners android: radius = "4dp" />
        </ shape>
    </ item>
    <item android: state_pressed = "true">
        <shape xmlns: android = "http://schemas.android.com/apk/res/android">
            <!-Line width, color gray->
            <stroke android: width = "1dp" android: color = "# ffea5514"> </ stroke>
            <!-Rectangle Fillet Radius->
            <corners android: radius = "4dp" />
        </ shape>
    </ item>
    <item android: state_activated = "true">
        <shape xmlns: android = "http://schemas.android.com/apk/res/android">
            <!-Line width, color gray->
            <stroke android: width = "1dp" android: color = "# ffea5514"> </ stroke>
            <!-Rectangle Fillet Radius->
            <corners android: radius = "4dp" />
        </ shape>
    </ item>
</ selector> 


Haha finished, we can add to the Grideview item layout, the specific is added in the root layout or under the control of the specific can be.
OK, let's take a look at the activity code:


package com.losileeya.selectmaster;

import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.losileeya.selectmaster.adapter.TagAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView (R.id.gridview)
    GridView gridview;
    private TagAdapter mAdapter;
    private List <String> mDatas;
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        ButterKnife.bind (this);
        initData ();
        doEvent ();
    }
    private void initData () {
        mDatas = new ArrayList <> ();
        mDatas.add ("Oriental Wealth? Finance");
        mDatas.add ("58 same city");
        mDatas.add ("soufangwang");
        mDatas.add ("Ctrip Travel Network");
        mDatas.add ("Baidu map");
        mDatas.add ("12306? Travel");
        mDatas.add ("Century Jiayuan");
        mDatas.add ("catch network");
        mDatas.add ("easy car network");
        mDatas.add ("Where is the network");
        mDatas.add ("Vipshop");
    }
    private void doEvent () {
        gridview.setOnItemClickListener (new AdapterView.OnItemClickListener () {

            @Override
            public void onItemClick (AdapterView <?> parent, View view,
                                    int position, long id) {
                Snackbar.make (gridview, mDatas.get (position), Snackbar.LENGTH_SHORT)
                        .show ();

            }
        });
    gridview.setChoiceMode (GridView.CHOICE_MODE_SINGLE); // radio mode
        // By default the first item is selected
        mAdapter = new TagAdapter (MainActivity.this, mDatas, 0);
        gridview.setAdapter (mAdapter);
        gridview.post (new Runnable () {
            @Override
            public void run () {
                gridview.setItemChecked (0, true);
                gridview.setSelected (true);
                gridview.setSelection (0);
            }
        });
    }
} 


Look at the code above: general implementation steps


The icon in 1.GridView writes out selector in drawable, which lists android:state_pressed's picture resources and state_selected picture resources in the selector file.

2.gridview.setchoicemode (Gridview.choice_mode_single);//single-selection mode

3.GridView onitemclickedlistener Monitor, call view.selected (true) for the currently selected view

4.gridview.setitemchecked (0, true); gridview.setselection (0); The first one is selected by default

Precautions

The state_activated state attribute in Selector.xml must be used in versions androidAPI-11 and above.


Written here is finished, basically is the project can be used (check here does not say, use almost not to speak) do not know how to help you, although very simple is not the understanding of selector further.



Demo Portal: Selectmaster.rar



Android Real-CardView selector and Grideview item pressed state reserved Selector (state_activated) implementation


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.