Подтвердить что ты не робот

Как использовать SwipeRefreshLayout?

Фон

Google недавно опубликовал обновление для своей библиотеки поддержки, которая теперь имеет новый видSwipeRefreshLayout.

Представление позволяет обернуть другое представление, в то же время поддерживая смахивание вниз для выполнения операции обновления.

Скриншот:

enter image description here

Проблема

Google не предоставил образец (по крайней мере, пока тот, который я не могу найти), поэтому я попробовал использовать его сам.

Сначала у меня возникал сбой (NPE) всякий раз, когда я проводил, но потом я узнал об этом, потому что я не предоставил ему "OnRefreshListener".

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

Вот 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"
    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>

Код, хотя он ничего особенного не делает:

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
          }
      });
    }
  }

Вопрос

Как правильно использовать это представление?

Как мне это настроить? На данный момент это просто черная линия...

4b9b3361

Ответ 1

Не знаю, что это за класс ActionBarActivity, который вы расширяете, но у меня все работает нормально, используя FragmentActivity

public class ActivityMain extends FragmentActivity implements OnRefreshListener {

    private SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        super.onCreate(savedInstanceState);
    }

    @Override
    public void onRefresh() {
        Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }, 2000);
    }
}

Стоит отметить, что я скопировал и вставил ваш макет XML точно так же, как он есть

С точки зрения настройки, вы действительно ничего не можете сделать, кроме как изменить цвет цветной панели, вызвав setColorScheme (int colorResId, int colorResId, int colorResId, int colorResId);

например,

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

    <color name="blue">#0099CC</color>
    <color name="purple">#9933CC</color>
    <color name="green">#669900</color>
    <color name="orange">#FF8800</color>

</resources>

mSwipeRefreshLayout.setColorScheme(R.color.blue, R.color.purple, R.color.green, R.color.orange);

Это действительно разочаровывающее дополнение. Чувствительность при обновлении достаточно высока, и нет никаких настроек, чтобы изменить это

Изменить

Я написал это, когда этот класс (и класс ActionBarActivity) только что был добавлен в SDK. Таким образом, некоторые вещи изменились с того момента, когда я написал этот ответ. Кроме того, тип используемого действия не должен влиять на это решение.

setColorScheme устарел, вместо него следует использовать setColorSchemeResources(int... colorResIds). (Вы можете добавить столько идентификаторов цветов, сколько захотите).

setDistanceToTriggerSync(int distance) также можно использовать для установки того, как далеко пользователь должен провести пальцем, чтобы вызвать обновление.

Я рекомендую ознакомиться с официальной документацией, чтобы узнать, что еще может предложить класс.

Ответ 2

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>

colors.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>

Ответ 4

Вы можете просто использовать метод ниже (я использую swipelayout в расширяемом списке) 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>

используемые цвета

<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);
                }
            });

Вы можете установить swipeView.setRefreshing(false); в значение false или true в соответствии с вашим требованием этот механизм swipeing будет работать в android на уровне API

Ответ 5

SwipeRefreshLayout с Kotlin

Код XML файла

 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:layout_width="0dp"
        android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="90dp" app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="93dp" app:layout_constraintEnd_toEndOf="parent"
        android:id="@+id/swipe_refresh_layout"
>
    <androidx.recyclerview.widget.RecyclerView
            android:layout_width="0dp"
            android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="90dp" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="93dp" app:layout_constraintEnd_toEndOf="parent"
            android:id="@+id/recyclerView"
    />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

Код активности

Объявите следующий код над методом oncreate

    var mSwipeRefreshLayout: SwipeRefreshLayout? = null

Объявите следующий код внутри метода oncreate после строки setContentView

mSwipeRefreshLayout= findViewById<SwipeRefreshLayout>(R.id.swipe_refresh_layout)
mSwipeRefreshLayout!!.setOnRefreshListener {
   //API Calls
}

При успешном вызове API или при отказе API

                mSwipeRefreshLayout!!.isRefreshing = false

Ответ 6

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);


 }


}