java - 使用 Json 创建水平滚动条?
问题描述
我正在尝试创建像 Google Play 一样的 CardView ScrollBar UI。
我正在学习本教程,但停留在模型类中,无法进一步移动。
我的 Json 是这样的:
{
"Cards": {
"Recently Updated": [
{
"Name": "A",
"img": "a.png",
"link": "alink.com"
},
{
"Name": "B",
"img": "b.png",
"link": "blink.com"
},
{
"Name": "C",
"img": "c.png",
"link": "clink.com"
}
],
"Newly Arrives": [
{
"Name": "A",
"img": "a.png",
"link": "alink.com"
},
{
"Name": "L",
"img": "L.png",
"link": "Llink.com"
},
{
"Name": "z",
"img": "z.png",
"link": "zlink.com"
}
]
}
}
请帮助创建相同的。
我怎样才能像上图一样添加cardview滚动条
解决方案
要创建模型,您需要遵循 JSON 向您展示的树。从外部矩形到内部矩形查看图片。
首先,您将所有 JSON 内容作为一个块。
这将是我的第一个模型课
MainCard.java
public class MainCard {
@SerializedName("Cards")
public Cards cards;
}
请注意,我的 MainCard(我的第一个也是最大的矩形)包含在 Cards 矩形内。这就是它具有公共变量 Cards 的原因。
其次,让我们移动到第二个矩形。(牌)
卡片.java
public class Cards {
@SerializedName("Recently Updated")
public List<Item> recentlyUpdates;
@SerializedName("Newly Arrives")
public List<Item> newlyArrives;
}
Cards 矩形里面有两个矩形,最近更新和新到,这就是我创建这两个变量的原因。
最后,请注意“最近更新”内的矩形和“新到”内的矩形是一些东西的列表(我称之为项目 - [名称,img,链接])。这就是我将最近更新的变量创建为列表的原因。
项目.java
public class Item {
@SerializedName("Name")
public String name;
@SerializedName("img")
public String img_url;
public String link;
}
笔记
@SerializedName 应该包含您的 JSON 提供的完全相同的名称,例如,在 Cards.java 中,我的变量名称是 recentUpdates 并且我的 @SerializedName("") 是最近更新的(这与我们在 JSON 响应中的名称完全相同) . 但是,如果您的变量名与您的 JSON 相同,则无需输入@SerializedName,这发生在 Item.java 中的链接变量中。
改造
如果您的 JSON 在在线服务器上,您应该使用一些库来调用此内容。我建议您按 square 使用 retrofit 2。
将依赖项添加到依赖项部分下的 build.gradle (Module:app) 文件中。
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// Retrofit 2
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
}
然后你应该创建一个服务来调用你的 JSON 对象。
CardsService.java(注意:这是一个接口)
public interface CardsService {
String BASE_URL = "http://yourbaseurl.api/";
@GET("endpoint")
Call<MainCard> getCards();
}
在您的 MainActivity 中,您调用该服务来获取 JSON 数据。
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(CardsService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
CardsService service = retrofit.create(CardsService.class);
Call<MainCard> call = service.getCards();
call.enqueue(new Callback<MainCard>() {
@Override
public void onResponse(Call<MainCard> call, Response<MainCard> response) {
if (response.isSuccessful()) {
// Got a successful response (Code 200...300)
MainCard mainCard = response.body();
if (mainCard != null && mainCard.cards != null) {
List<Item> recentlyUpdates = mainCard.cards.recentlyUpdates;
List<Item> newlyArrives = mainCard.cards.newlyArrives;
// Use your information to set up the recyclerview as the tutorial you
// showed describe.
setupRecyclerView(recentlyUpdates, newlyArrives);
}
} else {
// Got a unsucessful response (Code 401, 405, 409...)
}
}
@Override
public void onFailure(Call<MainCard> call, Throwable t) {
// Failed to connect to the server
// Possible causes: No internet connection, Server is broken.
}
});
}
}
如果你不是改装家庭,你应该阅读一些关于 medium 的教程,就像这个一样,你也可以查看这个项目来了解更多关于这个主题的信息。
编辑
如何在回收站视图中设置项目?
获得成功响应后,您可以调用该setupRecyclerView(List<Item> items)
方法在回收站视图中显示您的项目。我将只使用最近更新列表,然后您以您希望显示两者的方式进行自定义。
if (response.isSuccessful()) {
// Got a successful response (Code 200...300)
MainCard mainCard = response.body();
if (mainCard != null && mainCard.cards != null) {
List<Item> recentlyUpdates = mainCard.cards.recentlyUpdates;
List<Item> newlyArrives = mainCard.cards.newlyArrives;
// ***** Use your information to set up the recyclerview. *****
// I am going to set up only the recentlyUpdates list.
setupRecyclerView(recentlyUpdates);
}
}
在您的 xml 文件中创建一个 RecyclerView
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
回到您的活动中,投射回收器视图,添加布局管理器和适配器。
private void setupRecyclerView(List<Item> itemsList) {
RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(new MyCardsAdapter(itemsList, this));
}
MyCardsAdapter.java
public class MyCardsAdapter extends RecyclerView.Adapter<MyCardsAdapter.ItemHolder> {
private List<Item> itemsList;
private Context context;
public MyReposAdapter(List<Item> itemsList, Context context) {
this.itemsList = itemsList;
this.context = context;
}
@NonNull
@Override
public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_item, parent, false);
return new ItemHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ItemHolder holder, int position) {
// Get each item.
Item singleItem = itemsList.get(position);
// singleItem is each Item.java you created. And holder contains the widgets you created in single_item.xml to display the items information.
holder.textViewName.setText(singleItem.name);
holder.textViewImage.setText(sigleItem.image_url);
holder.textViewLink.setText(singleItem.link);
}
@Override
public int getItemCount() {
return itemList.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public TextView textViewImage;
public TextView textViewLink;
public ItemHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_name);
textViewImage = itemView.findViewById(R.id.text_image);
textViewLink = itemView.findViewById(R.id.text_link);
}
}
}
single_item.xml
这是将在 recyclerview 中显示的每个项目的布局。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<!-- 1. Name -->
<TextView
android:id="@+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Name"
android:textSize="22sp"
android:textColor="@color/colorBlack"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintTop_toTopOf="parent"/>
<!-- 2. Image URL -->
<TextView
android:id="@+id/text_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="URL"
android:textSize="18sp"
android:textColor="@color/colorPrimary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintTop_toBottomOf="@+id/text_name"/>
<!-- 3. Link -->
<TextView
android:id="@+id/text_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Language"
android:textSize="16sp"
android:textColor="@color/colorBlack"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintTop_toBottomOf="@+id/text_url"/>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
推荐阅读
- angular - Circle CI angular Unexpected token )
- webpack - webpack 多个入口点(数组)按顺序排列
- .net - gitlab ci yaml 为 dontnet 框架和 .net 核心配置
- cucumber - 在'step 2'中执行'step 1' - cypress+cucumber
- numba - Numba 缓存和迭代求解
- azure - ADSTS50011:请求中指定的回复 URL 与为应用程序配置的回复 URL 不匹配
- html - 在 CSS 中排序大小不等的元素
- python - 如何解决 PyQt5 的 pyOpenGL glViewport 错误
- javascript - 画布单个对象旋转而不是全部
- azure - 使用 sendgrid 发送电子邮件时出错