我正在使用Volley进行请求,并希望在加载数据时添加微光。我可以使用Handler来执行它,但是我不知道什么时候会有数据,并且无法设置确切的时间。
这里是我的片段中的代码。我想将值false
设置为变量isShimmer
,它是如此之快,以至于我的微光无法运行:
String url = "my_url";
JsonArrayRequest getArticleOfTheDayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
response -> {
try {
for(int i = 0; i < response.length(); i++){
JSONObject articleObject = response.getJSONObject(i);
int article_id = articleObject.getInt("article_id");
String title = articleObject.getString("title");
String text = articleObject.getString("text");
ArticleOfTheWeek articleOfTheWeek = new ArticleOfTheWeek(article_id, title, text);
articleOfTheWeekList.add(articleOfTheWeek);
}
articleOfTheWeekAdapter = new ArticleOfTheWeekAdapter(getContext(), articleOfTheWeekList);
recyclerView.setAdapter(articleOfTheWeekAdapter);
articleOfTheWeekAdapter.isShimmer = false;
articleOfTheWeekAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
},
error -> Log.d("Error.Response", error.getMessage() + " ")
);
这里是我的适配器中的代码:
public boolean isShimmer = true;
int shimmerNumber = 2;
@Override
public void onBindViewHolder(@NonNull final ArticleOfTheWeekViewHolder holder, int position) {
final ArticleOfTheWeek articleOfTheWeek = articleOfTheWeekList.get(position);
if(isShimmer)
{
holder.shimmerFrameLayout.startShimmer();
}else
{
holder.shimmerFrameLayout.stopShimmer();
holder.shimmerFrameLayout.setShimmer(null);
holder.textViewTitle.setBackground(null);
holder.textViewTitle.setText(articleOfTheWeek.getTitle());
holder.textViewDesc.setBackground(null);
holder.textViewDesc.setText(Html.fromHtml(articleOfTheWeek.getText()));
}
}
如您所见,如果我将isShimmer
设置为true,则微光将无限运行。因此,当所有数据都装入以更改isShimmer
我已经使用this库来获取数据时显示微光效果。首先在xml文件中为您的闪烁布局设置可见性,然后在活动shimmerViewContainer.startShimmer()
的开始处开始闪烁。
在活动文件中将数据设置到适配器后,在排球方法中设置shimmerViewContainer.stopShimmer()
。
以及在onPause()
和onDestroy()
上停止闪烁
如果将微光放在父布局中而不是在适配器布局中,可能会更容易保持微光状态。我希望采用以下方法:
1。在活动/片段的布局内部
<RelativeLayout>
<RecyclerView/>
<FrameLayout
android:id="@+id/shimmer_container">
<!-- show hide this FrameLayout container depend on state of data loading/loaded -->
<include layout="@layout/list_shimmer"/>
</FrameLayout>
</RelativeLayout>
[list_shimmer可能看起来像:
<com.facebook.shimmer.ShimmerFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:shimmer_auto_start="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/just_like_adapter_item_layout" />
<include layout="@layout/just_like_adapter_item_layout" />
<!-- repeat until it's enough to fill the screen -->
</LinearLayout>
</com.facebook.shimmer.ShimmerFrameLayout>
重要属性:
app:shimmer_auto_start =“ true”
因此,您无需以编程方式启动微光。
2。活动/片段
void initList(List<Data> items) {
adapter.setItems(items);
shimmer_container.setVisibility(View.GONE);
}