Пустые элементы списка в представлении переработчика - PullRequest
1 голос
/ 24 июня 2019

Когда приложение запускается, первые 6 элементов списка (которые содержатся на полутора экранах) из 44 элементов изначально пусты. Как только я прокручиваю вниз, а затем поднимаюсь, они, наконец, отображаются. Я хочу, чтобы эти списки загружались сразу после запуска приложения.

Я попытался решить, добавив

mLayoutManager.setStackFromEnd(true);

mLayoutManager.setReverseLayout(true);

перед настройкой компоновщика менеджера просмотра. Но позже я узнал, что это служит какой-то другой цели.

Вот часть кода -

MainActivity.java

public class MainActivity extends AppCompatActivity {

    RecyclerView rv;
    LinearLayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv = (RecyclerView) findViewById(R.id.DepList);
        rv.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);

        rv.setLayoutManager(mLayoutManager);
        DepAdapter dep = new DepAdapter();
        rv.setAdapter(dep);
    }
}

DepAdapter.java

public class DepAdapter extends RecyclerView.Adapter<DepAdapter.DepHolder> {

    String[] depName;
    String[] detail;
    int klm=0;

    public DepAdapter()
    {
        depName=new String[44];
        detail=new String[44];

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://data.police.uk/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonHolder jsonHolder = retrofit.create(JsonHolder.class);

        Call<List<FetchData>> call = jsonHolder.getDATA();


        call.enqueue(new Callback<List<FetchData>>() {
            @Override
            public void onResponse(Call<List<FetchData>> call, Response<List<FetchData>> response) {

                if(!response.isSuccessful())
                {
                    System.out.println("Server Error");
                    return;
                }

                List<FetchData>  posts = response.body();

                for (FetchData fetchData : posts ){
                    depName[klm]=fetchData.getName();
                    detail[klm]=fetchData.getId();
                    klm++;
                }
            }

            @Override
            public void onFailure(Call<List<FetchData>> call, Throwable t) {
                System.out.println("FAILED TO FETCH");
            }
        });
    }

    @NonNull
    @Override
    public DepHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.list_theme,viewGroup,false);

        return new DepHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DepHolder depHolder, int i) {

        String title = depName[i];
        String brief = detail[i];

        depHolder.head.setText(title);
        depHolder.text.setText(brief);
    }

    @Override
    public int getItemCount() {
        return depName.length;
    }

    public class DepHolder extends RecyclerView.ViewHolder{

        ImageView imgIcon;
        TextView text,head;

        public DepHolder(@NonNull View itemView) {
            super(itemView);

            imgIcon=(ImageView) itemView.findViewById(R.id.imgIcon);
            text=(TextView)itemView.findViewById(R.id.text);
            head=(TextView)itemView.findViewById(R.id.head);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingStart="5dp"
    android:paddingLeft="5dp"
    android:paddingTop="5dp"
    >

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/backbutton"
        android:onClick="backfromdep"
        android:id="@+id/backfromdep"
        android:layout_marginBottom="5dp"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textSize="20sp"
        android:layout_marginLeft="10dp"
        android:text="Search dep option here"
        android:textColor="#000"
        />
</LinearLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/DepList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:scrollbars="vertical"
    >

</android.support.v7.widget.RecyclerView>
</LinearLayout>

list_theme.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/border"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_background"
        android:layout_margin="10dp"
        android:id="@+id/imgIcon"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kent Police"
        android:textColor="#000"
        android:textSize="18sp"
        android:layout_marginTop="10dp"
        android:id="@+id/head"
        />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Kent Police"
            android:textColor="#000"
            android:textSize="13sp"
            android:layout_marginTop="5dp"
            android:id="@+id/text"
            />


    </LinearLayout>

</LinearLayout>

1 Ответ

0 голосов
/ 24 июня 2019

В вашем коде есть некоторые архитектурные проблемы (например, вы не должны делать сетевой запрос от адаптера и особенно не из конструктора), но игнорируете его, чтобы ответить на ваш реальный вопрос ....

Когда выЧтобы обновить окно повторного просмотра, поскольку в адаптере отображаются новые данные, необходимо вызвать один из методов notify. notifyDataSetChanged будет проще всего сделать недействительным весь список.

public void onResponse(Call<List<FetchData>> call, Response<List<FetchData>> response) {

    if (!response.isSuccessful()) {
        System.out.println("Server Error");
        return;
    }

    List<FetchData>  posts = response.body();

    for (FetchData fetchData : posts ) {
        depName[klm]=fetchData.getName();
        detail[klm]=fetchData.getId();
        klm++;
    }

    notifyDataSetChanged(); // Trigger an update to the recyclerview this is attached to
}

Надеюсь, это поможет!

...