使用Json创建水平滚动条? [英] Creating Horizontal Scroll Bar Using Json?

查看:88
本文介绍了使用Json创建水平滚动条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create the CardView ScrollBar UI like Google Play.

我正在关注

I was following this tutorial but stuck at the models classes and can't move further.

我的杰森(Json)就是这样:

My Json is like this:

{
  "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"
      }
    ]
  }
} 

请帮助创建相同的内容.

Please help to create the same.

我想这样实现:

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

How can i add cardview scrollbar like above image

推荐答案

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

To create a model you need to follow the tree the JSON is showing you. Look at the picture from the outside rectangles to the inside rectangles.

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

First of all, you have all the JSON content as a block.

这将是我的第一堂课

MainCard.java

public class MainCard {

    @SerializedName("Cards")
    public Cards cards;

}

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

Notice that my MainCard (my first and biggest rectangle) contains inside the Cards rectangle. That is why it has the public variable Cards.

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

Second, let's move to the second rectangle. (Cards)

Cards.java

public class Cards {

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

}

卡片"矩形内部有两个矩形,最近更新"和新到达",这就是为什么我创建了这两个变量的原因.

The Cards rectangle has two rectangles inside it, Recently Updated and Newly Arrives, that is why I created this two variables.

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

Finally, notice that the rectangle inside Recently Updated and the rectangles inside Newly Arrives is a List of something (which I called Item - [name, img, link]). That's why I created the recentlyUpdated variable as a List.

Item.java

public class Item {

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

}

注释

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

@SerializedName should contain the exact same name your JSON provides, for example, in Cards.java, my variable name is recentlyUpdates and my @SerializedName("") is Recently Updated (which is the exact same name we have in the JSON response). However, if your variable name is the same as your JSON, you do not need to put @SerializedName, this happens in Item.java in the link variable.

改造

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

If you JSON is on an online server, you should use some library to call this content. I would recommend you to use retrofit 2 by square.

在依赖项"部分下,将依赖项添加到build.gradle(Module:app)文件中.

Add the dependencies to your build.gradle (Module:app) file under the dependencies section.

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对象的服务.

Then you should create a service that will call your JSON object.

CardsService.java (注意:这是一个接口)

CardsService.java (Note: this is an interface)

public interface CardsService {

    String BASE_URL = "http://yourbaseurl.api/";

    @GET("endpoint")
    Call<MainCard> getCards();

}

然后在MainActivity中调用该服务以获取JSON数据.

And in your MainActivity you call the service to get the JSON data.

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

如果您不熟悉翻新,则应该阅读一些中等水平的教程,如

If you are not family with retrofit you should read some tutorials on medium, as this one, and you can also check this project to learn more about the topic.

编辑

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

获得成功的响应后,您可以调用setupRecyclerView(List<Item> items)方法以在回收者视图中显示您的物品.我将仅使用最近更新"列表来完成此操作,然后按照您希望同时显示两者的方式进行自定义.

After you get a successful response you can call the setupRecyclerView(List<Item> items) method to display your items in a recycler view. I'll do it using only the recentlyUpdates list, then you customize in the way you want to display both.

                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

Create a RecyclerView in your xml file

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

返回您的活动,投射回收站视图,添加布局管理器和适配器.

Back in your activity, cast the recycler view, add the layout manager and the adapter.

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

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

This is the layout of each item that will be displyed in the 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>

这篇关于使用Json创建水平滚动条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆