首页 > 解决方案 > 具有不同参数的相同片段的基本片段

问题描述

我正在使用 BottomNavigationView 的内置样板来构建一个包含三个从 api 获取数据的片段的应用程序。

所有三个片段都使用不同的参数从同一个 api 调用数据。但是在所有片段中都使用了相同的代码,只有categoryid每个 api 调用中的更改。扩展抽象基础片段是减少代码重复的有效方法吗?如何将参数categoryid从子片段传递到基本片段?

我不想为所有三个菜单项创建一个片段和一个布局,以便保存每个片段的状态并避免在每次导航更改时进行 api 调用。

任何指导将不胜感激。

public class ABCFragment extends Fragment {

    private RestAPI restAPI;
    private RecyclerView recyclerView;
    static Context context;
    private boolean mTwoPane = false;
    int layoutId = 0;
    int categoryid = 1; //default value
    int langId = 1;

    private FragmentABCBinding abcBind;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
    
        abcBind = FragmentABCBinding.inflate(inflater, container, false);
        context = this.getActivity().getApplicationContext();

        if (abcBind.detail != null) {
            mTwoPane = true;
        }

        recyclerView = abcBind.list;
        recyclerView.setLayoutManager(new LinearLayoutManager(context));

    
        createRestAPI();
        restAPI.getAPI(langId, categoryid).enqueue(abcCallback); //CATEGORYID is the argument which differentiates each fragment
        return abcBind.getRoot();
    }



    private void createRestAPI() {
        HttpService okhttpClient = new HttpService(context);
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .client(okhttpClient.getHttpClient())
                .baseUrl(RestAPI.ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        restAPI = retrofit.create(restAPI.class);
    }


    Callback<ListWrapper<ResponseList>> abcCallback = new Callback<ListWrapper<ResponseList>>() {
        @Override
        public void onResponse(Call<ListWrapper<ResponseList>> call, Response<ListWrapper<ResponseList>> response) {
            if (response.isSuccessful()) {
                Log.d("Callback", " Message: " + response.body().items);
                List<ResponseList> re = new ArrayList<>();
                re.addAll(response.body().items);
                ListViewAdapter adapter = new ListViewAdapter(re);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener((ClickListener<abcList>) (view, data, position) -> {
                    Toast.makeText(context,"Position = "+position+"\n Item = "+data.getNo(), Toast.LENGTH_SHORT).show();

          
                    String no = data.getNo();
                    Bundle bundle = new Bundle();
                    bundle.putString("no", no);

                    DetailViewFragment detailedFragment = new DetailViewFragment();
                    detailedFragment.setArguments(bundle);

                    if (mTwoPane) {
                        layoutId = abcBind.detail.getId();
                    }
                    else {
                        layoutId = abcBind.fragment.getId();
                    }


                    MainActivity activity = (MainActivity) view.getContext();
                    activity
                            .getSupportFragmentManager()
                            .beginTransaction()
                            .replace(layoutId, detailedFragment)
                            .addToBackStack(null)
                            .commit();
                });

            } else {
                Log.d("Callback", "Code: " + response.code() + " Message: " + response.message());
            }
        }

        @Override
        public void onFailure(Call<ListWrapper<ResponseList>> call, Throwable t) {
            t.printStackTrace();
        }
    };

}

标签: androidandroid-fragments

解决方案


一种方法是让你ABCFragment abstract使用一个abstract函数 int getCategoryId(),除了其余的代码。所有其他 3 Fragments,扩展ABCFragment',将只需要实现这个函数并返回所需categoryId的。

通过将此行更改为:

restAPI.getAPI(langId, getCategoryId()).enqueue(abcCallback);

categoryId 通过方法获得。

所有扩展的片段 ABCFragment,都将拥有它的布局和所有其他已经定义和可用的方法。


推荐阅读