首页 > 解决方案 > 我可以在片段内创建方法吗?

问题描述

我对 android studio 有点陌生。我有一些问题要问。如何在片段中本地添加方法以及如何在应用程序中显示它?我正在尝试使用 Retrofit 使用 REST API 从现有数据库中显示我的数据,以在 Android 片段中显示它。我尝试了来自 YouTube 的不同教程,但我不确定。

这是 RecyclerView 适配器的代码:

    package com.example.cyberview_android1;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerHolder> {

    List<ProfileModel> models;


    public RecyclerViewAdapter(List<ProfileModel> models) {
        this.models = models;
    }

    @NonNull
    @Override
    public RecyclerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_row, viewGroup, false);
        return new RecyclerHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerHolder holder, int position) {

        recyclerHolder.textView.setText(models.get(i).profile_cat);
    }

    @Override
    public int getItemCount() {
        return models.size();
    }

    public class RecyclerHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public RecyclerHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textTitle);
        }
    }
}

这是片段的代码:

package com.example.cyberview_android1;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ProfileFragment extends Fragment {
    RecyclerView rvProfile;


    public ProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rvProfile = rvProfile.findViewById(R.id.rv_profile);
        rvProfile.setLayoutManager(new LinearLayoutManager(ProfileFragment.this));
        RetrofitInterface retrofitInterface = RetrofitInstance.getRetrofitInstance().create(RetrofitInterface.class);
        Call<List<ProfileModel>> listCall = retrofitInterface.getAllProfile();
        listCall.enqueue(new Callback<List<ProfileModel>>() {
            @Override
            public void onResponse(Call<List<ProfileModel>> call, Response<List<ProfileModel>> response) {
                parseData(response.body());
            }

            @Override
            public void onFailure(Call<List<ProfileModel>> call, Throwable t) {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    private void parseData(List<ProfileModel> body) {
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(body);
        rvProfile.setAdapter(recyclerViewAdapter);
    }
}package com.example.cyberview_android1;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ProfileFragment extends Fragment {
    RecyclerView rvProfile;


    public ProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rvProfile = rvProfile.findViewById(R.id.rv_profile);
        rvProfile.setLayoutManager(new LinearLayoutManager(ProfileFragment.this));
        RetrofitInterface retrofitInterface = RetrofitInstance.getRetrofitInstance().create(RetrofitInterface.class);
        Call<List<ProfileModel>> listCall = retrofitInterface.getAllProfile();
        listCall.enqueue(new Callback<List<ProfileModel>>() {
            @Override
            public void onResponse(Call<List<ProfileModel>> call, Response<List<ProfileModel>> response) {
                parseData(response.body());
            }

            @Override
            public void onFailure(Call<List<ProfileModel>> call, Throwable t) {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    private void parseData(List<ProfileModel> body) {
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(body);
        rvProfile.setAdapter(recyclerViewAdapter);
    }
}

这是改造实例代码:

package com.example.cyberview_android1;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitInstance {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://localhost:5000/api/";

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }


}

界面:

package com.example.cyberview_android1;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface RetrofitInterface {

    @GET("/employee/profile")
    Call<List<ProfileModel>> getAllProfile();


}

和模型:

package com.example.cyberview_android1;

import com.google.gson.annotations.SerializedName;

public class ProfileModel {

    @SerializedName("category")
    String profile_cat;

    @SerializedName("description")
    String profile_desc;

    @SerializedName("date")
    String date;

    public String getProfile_cat() {
        return profile_cat;
    }

    public void setProfile_cat(String profile_cat) {
        this.profile_cat = profile_cat;
    }

    public String getProfile_desc() {
        return profile_desc;
    }

    public void setProfile_desc(String profile_desc) {
        this.profile_desc = profile_desc;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

此外,我收到了来自 Holders 和 View 组的错误。我按照教程中的步骤进行操作,但我保证我没有遗漏任何内容。

在此处输入图像描述

我将衷心感谢您的帮助。

标签: javaandroidandroid-studio

解决方案


改变 :

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

至:

View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_customer_customlist , parent , false);

和:

recyclerHolder.textView.setText(models.get(position).profile_cat);

至:

holder.textView.setText(models.get(position).profile_cat);

这将解决您的问题,但如果您想知道适配器到底是什么,我会为您简要解释一下:

适配器通常有 4 个主要部分:

1- onCreateViewHolder 2- ViewHolder 子类 3- onBindViewHolder 4- getItemCount

1-in onCreateViewHolder 您将设置您的 viewHolder xml 视图,然后返回一个 ViewHolder 对象。(这是您创建 itemView 实例的地方)(这里有两个参数,一个 ViewGroup 和一个 viewType ) ViewGroup 是您的 itemView 的父视图这意味着您在此方法中膨胀以创建视图对象的 xml 布局文件的父级:

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

viewtype 用于在您的回收器中实现多个 viewType,在您的场景中不是必需的,所以我只是跳过它。

2-在您的 viewHolder 类中,您可以访问您的 itemView 小部件。

3-in onBindViewHolder 将在您滚动或通过通知适配器更改数据集时调用,数据将根据您的模型通过其位置设置

4-getItemCount 将识别适配器中项目的大小。(在您的场景中它是模型):

List<ProfileModel> models;

推荐阅读