web-dev-qa-db-fra.com

Comment utiliser SwipeRefreshLayout?

Contexte

Google a récemment publié une mise à jour de sa bibliothèque de support , qui dispose désormais d'une nouvelle vue " SwipeRefreshLayout ". 

La vue permet d'envelopper une autre vue, tout en prenant en charge le glissement vers le bas afin d'effectuer une opération de rafraîchissement.

capture d'écran:

enter image description here

Le problème

Google n'a pas fourni d'échantillon (du moins pas que je puisse trouver pour le moment) et j'ai donc essayé de l'utiliser moi-même. 

Au début, j'ai eu un crash (NPE) à chaque fois que j'ai glissé, mais j'ai ensuite découvert que c'était parce que je n'avais pas fourni de "OnRefreshListener".

Mais je ne comprends toujours pas comment l'utiliser, et encore moins le personnaliser

Voici le XML du fichier de mise en page:

<Android.support.v4.widget.SwipeRefreshLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:id="@+id/container"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context="com.example.swiperefreshlayouttest.MainActivity"
    tools:ignore="MergeRootFrame" >

    <ScrollView
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content" >

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:orientation="vertical" >

            <TextView
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:text="TTT"
                Android:textSize="40sp" />

            <TextView
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:text="TTT"
                Android:textSize="40sp" />

            <TextView
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:text="TTT"
                Android:textSize="40sp" />

            <TextView
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:text="TTT"
                Android:textSize="40sp" />

            <TextView
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:text="TTT"
                Android:textSize="40sp" />
        </LinearLayout>
    </ScrollView>

</Android.support.v4.widget.SwipeRefreshLayout>

Code, bien qu'il ne fasse rien de spécial:

public class MainActivity extends ActionBarActivity
  {
  @Override
  protected void onCreate(final Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final SwipeRefreshLayout swipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.container);
    swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener()
      {
        @Override
        public void onRefresh()
          {
          // do nothing
          }
      });
    }
  }

La question

Quelle est la bonne façon d'utiliser cette vue?

Comment puis-je le personnaliser? Actuellement, c'est juste une ligne noire ...

15
android developer

MainActivity.Java

public class MainActivity extends ActionBarActivity {
    TextView textView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    static int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.scrollTextView);

    // /You will setup the action bar with pull to refresh layout
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);

     mSwipeRefreshLayout.setColorScheme(R.color.blue,
     R.color.green, R.color.orange, R.color.purple);
    mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.e(getClass().getSimpleName(), "refresh");
            new GetLinks().execute();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public class GetLinks extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

            e.printStackTrace();

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
         //Here you can update the view
        textView.setText(textView.getText().toString()+"--New Content Added" + ++count);

        // Notify swipeRefreshLayout that the refresh has finished
        mSwipeRefreshLayout.setRefreshing(false);
    }

}

}

activity_main.xml

<Android.support.v4.widget.SwipeRefreshLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:id="@+id/container"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent" >

    <ScrollView
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content" >
            <TextView
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:id="@+id/scrollTextView"
                Android:text="TTT"
                Android:textSize="40sp" />
    </ScrollView>

</Android.support.v4.widget.SwipeRefreshLayout>

couleurs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="blue" type="color">#FF33B5E5</item>
    <item name="purple" type="color">#FFAA66CC</item>
    <item name="green" type="color">#FF99CC00</item>
    <item name="orange" type="color">#FFFFBB33</item>

</resources>
10
Zohra Khan
6
Simon

Vous pouvez simplement suivre la méthode ci-dessous (j’utilise swipelayout sur la liste Expandable) Test.xml

  <Android.support.v4.widget.SwipeRefreshLayout
        Android:id="@+id/swipe2"
        Android:layout_width="fill_parent"
        Android:layout_height="fill_parent"
        Android:layout_below="@id/RelativeTop"
        Android:background="@drawable/listbg" >

        <ExpandableListView
            Android:id="@+id/lvExp"
            Android:layout_width="fill_parent"
            Android:layout_height="fill_parent"
            Android:cacheColorHint="@Android:color/transparent"
            Android:groupIndicator="@null"
            Android:listSelector="@Android:color/white" />
    </Android.support.v4.widget.SwipeRefreshLayout>

ListHeader.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
         Android:layout_width="fill_parent"
         Android:layout_height="wrap_content"
         Android:background="@drawable/sectionbg"
         Android:orientation="horizontal"
         Android:padding="8dp" >

<ImageView
    Android:id="@+id/imageView1"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_gravity="center_vertical"
    Android:contentDescription="@string/contentdescription"
    Android:src="@drawable/expandbtn" />

<TextView
    Android:id="@+id/lblListHeader"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:layout_gravity="center_vertical"
    Android:layout_marginLeft="3dp"
    Android:text="this is test"
    Android:textColor="@Android:color/white"
    Android:textSize="17sp" />

ChildItem.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="fill_parent"
Android:layout_height="55dp"
Android:background="@color/GrayProductBackground" >

<TextView
    Android:id="@+id/lblListItem"
    Android:layout_width="match_parent"
    Android:layout_height="50dp"
    Android:layout_marginLeft="35dp"
    Android:layout_marginRight="20dp"
    Android:gravity="center_vertical"
    Android:paddingBottom="5dp"
    Android:textColor="@color/GrayTextProduct"
    Android:textSize="17sp" />

<ImageView
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignParentRight="true"
    Android:layout_alignRight="@+id/lblListItem"
    Android:layout_centerVertical="true"
    Android:layout_marginLeft="10dp"
    Android:layout_marginRight="10dp"
    Android:contentDescription="@string/arrowdescription"
    Android:gravity="center"
    Android:src="@drawable/navigationarrow" />

<RelativeLayout
    Android:layout_width="fill_parent"
    Android:layout_height="1dp"
    Android:layout_alignParentBottom="true"
    Android:background="@Android:color/white" >
</RelativeLayout>

couleurs utilisées

<color name="pDarkGreen">#8ec549</color>
<color name="pDarskSlowGreen">#c1f57f</color>
<color name="pLightGreen">#f7ffed</color>
<color name="pFullLightGreen">#d6d4d4</color>

Mainactivity.Java

        swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe2);
        swipeView.setColorSchemeResources(R.color.pDarkGreen, R.color.Gray, R.color.Yellow, R.color.pFullLightGreen);

swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {

                        swipeView.setRefreshing(false);

                    }
                    (new Handler()).postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            Log.d("Swipe", "Refreshing Number");

                        }
                    }, 0);
                }
            });

Vous pouvez définir swipeView.setRefreshing(false); sur false ou true en fonction de vos besoins Ce mécanisme de balayage fonctionnera dans tous les niveaux d'API d'Android.

1
Kirtikumar A.

activity_main.xml

 <Android.support.v4.widget.SwipeRefreshLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/swipe_refresh_layout"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content">

<Android.support.v4.view.ViewPager
    Android:id="@+id/viewpager"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    Android:visibility="gone"/>

MainActivity.Java

public class MainActivity extends AppCompatActivity
    implements SwipeRefreshLayout.OnRefreshListener {

      static ViewPager viewPager;

     @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    swipeRefreshLayout.setOnRefreshListener(this);
    swipeRefreshLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    swipeRefreshLayout.setRefreshing(true);
                                    setupViewPager(viewPager);
                                }
                            }
    );
}



 private void setupViewPager(ViewPager viewPager) {


swipeRefreshLayout.setRefreshing(false);


 }


} 
0
Hanisha