使用Json创建水平滚动条?

时间:2018-09-22 10:17:15

标签: java android android-recyclerview google-play

我正在尝试创建CardView ScrollBar UI,例如Google Play。

我正在遵循this教程,但停留在模型类上,无法继续前进。

我的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"
      }
    ]
  }
} 

请帮助创建相同的内容。

我想这样实现: enter image description here

如何添加上图所示的cardview滚动条

1 个答案:

答案 0 :(得分:2)

要创建模型,您需要遵循JSON向您显示的树。 查看从外部矩形到内部矩形的图片。

Json divided in blocks

首先,您将所有JSON内容作为一个块。

这将是我的第一堂课

MainCard.java

public class MainCard {

    @SerializedName("Cards")
    public Cards cards;

}

请注意,我的MainCard(我的第一个也是最大的矩形)包含在Cards矩形内。这就是为什么它具有公共变量Cards。

第二,让我们移动到第二个矩形。 (卡)

Cards.java

public class Cards {

    @SerializedName("Recently Updated")
    public List<Item> recentlyUpdates;
    @SerializedName("Newly Arrives")
    public List<Item> newlyArrives;

}

“卡片”矩形内部有两个矩形,“最近更新”和“新到达”,这就是为什么我创建了这两个变量。

最后,请注意,“最近更新”中的矩形和“新到达”中的矩形是某物的列表(我称其为Item-[name,img,link])。这就是为什么我将最近更新的变量创建为列表的原因。

Item.java

public class Item {

    @SerializedName("Name")
    public String name;
    @SerializedName("img")
    public String img_url;
    public String link;

}

注释

@SerializedName应该包含您的JSON提供的完全相同的名称,例如,在Cards.java中,我的变量名称是LatestUpdates,而我的@SerializedName(“”)是最近更新的(这与我们在JSON响应)。但是,如果您的变量名与JSON相同,则无需放置@SerializedName,这会在链接变量的Item.java中发生。

改造

如果JSON在在线服务器上,则应使用一些库来调用此内容。我建议您使用retrofit 2 by square

在“依赖项”部分下,将依赖项添加到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.
            }
        });
    }
}

如果您不熟悉翻新,则应该阅读一些this one中等形式的教程,也可以查看this project以了解有关该主题的更多信息。

编辑

如何在回收站视图中设置项目?

获得成功的响应后,您可以调用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

这是将在回收站视图中显示的每个项目的布局。

<?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>
相关问题