java - 如何动态创建类 Java

标签 java android android-fragments

我在 Android 中遇到 Java 类 问题,我想为一些 Fragment 创建一个 PaginationAdapter>,在我这样尝试之前

SickFragmentToAll.java

    adapter = new PaginationAdapterAll(getActivity(), fragment);

SickFragmentToCanceled

    adapter = new PaginationAdapterCanceled(getActivity(), fragment);

PaginationAdapterAll

public PaginationAdapter(Context context, SickFragmentToAll fragment) {
    this.context = context;
    this.mCallback = (PaginationAdapterCallback) fragment;
    results = new ArrayList<>();
}

PaginationAdapterCanceled

public PaginationAdapter(Context context, SickFragmentToCanceled fragment) {
    this.context = context;
    this.mCallback = (PaginationAdapterCallback) fragment;
    results = new ArrayList<>();
}

这是可行的,但效率不高,因为每个 Fragment 都有 1 个不同的 PaginationAdapter。如何使PaginationAdapter动态工作?

让它看起来像这样

SickFragmentToAll

    adapter = new PaginationAdapter(getActivity(), fragment);

SickFragmentToCanceled

    adapter = new PaginationAdapter(getActivity(), fragment);

分页适配器**

public PaginationAdapter(Context context, Fragment fragment) {
    this.context = context;
    this.mCallback = (PaginationAdapterCallback) fragment; // The problem here, I want to make it dynamically
    results = new ArrayList<>();
}

我尝试使用 Fragment fragment 但它不起作用

[更新] 完整代码

SickFragmentToAll.java

@SuppressWarnings("deprecation")
public class SickFragmentToAll extends Fragment implements PaginationAdapterCallback {

    private static final String TAG = "FRAGMENT_ALL";
    PaginationAdapter adapter;
    LinearLayoutManager linearLayoutManager;
    RecyclerView rv;
    ProgressBar progressBar;
    LinearLayout errorLayout;
    Button btnRetry;
    TextView txtError;
    View RootView;
    private static int PAGE_START = 1;
    private boolean isLoading = false;
    private boolean isLastPage = false;
    private int TOTAL_PAGES = 2;
    private int currentPage = PAGE_START;
    private MovieService movieService;
    private SickFragmentToAll fragment;

    public SickFragmentToAll(){

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

        RootView = inflater.inflate(R.layout.activity_main, container, false);
        super.onCreate(savedInstanceState);

        rv = (RecyclerView) RootView.findViewById(R.id.main_recycler);
        progressBar = (ProgressBar) RootView.findViewById(R.id.main_progress);
        errorLayout = (LinearLayout) RootView.findViewById(R.id.error_layout);
        btnRetry = (Button) RootView.findViewById(R.id.error_btn_retry);
        txtError = (TextView) RootView.findViewById(R.id.error_txt_cause);

        adapter = new PaginationAdapter(getActivity(), fragment);

        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        rv.setLayoutManager(linearLayoutManager);
        rv.setItemAnimator(new DefaultItemAnimator());

        rv.setAdapter(adapter);

        rv.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
            @Override
            protected void loadMoreItems() {
                isLoading = true;
                currentPage += 1;

                loadNextPage();
            }

            @Override
            public int getTotalPageCount() {
                return TOTAL_PAGES;
            }

            @Override
            public boolean isLastPage() {
                return isLastPage;
            }

            @Override
            public boolean isLoading() {
                return isLoading;
            }
        });

        movieService = MovieApi.getClient().create(MovieService.class);

        loadFirstPage();

        btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadFirstPage();
            }
        });

        return RootView;
    }

    private void loadFirstPage() {
        Log.d(TAG, "loadFirstPage: ");

        // To ensure list is visible when retry button in error view is clicked
        hideErrorView();

        callRootApi().enqueue(new Callback<Root>() {
            @Override
            public void onResponse(Call<Root> call, Response<Root> response) {
                // Got data. Send it to adapter
                hideErrorView();

                List<Result> results = fetchResults(response);
                progressBar.setVisibility(View.GONE);
                adapter.addAll(results);

                if (currentPage <= TOTAL_PAGES)
                    adapter.addLoadingFooter();
                else
                    isLastPage = true;
            }

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

    private List<Result> fetchResults(Response<Root> response) {
        Root root = response.body();
        return root.getResult();
    }

    private void loadNextPage() {
        Log.d(TAG, "loadNextPage: " + currentPage);

        callRootApi().enqueue(new Callback<Root>() {
            @Override
            public void onResponse(Call<Root> call, Response<Root> response) {
                adapter.removeLoadingFooter();
                isLoading = false;

                List<Result> results = fetchResults(response);
                adapter.addAll(results);

                if (currentPage != TOTAL_PAGES)
                    adapter.addLoadingFooter();
                else
                    isLastPage = true;
            }

            @Override
            public void onFailure(Call<Root> call, Throwable t) {
                t.printStackTrace();
                adapter.showRetry(true, fetchErrorMessage(t));
            }
        });
    }

    private Call<Root> callRootApi() {
        return movieService.getRoot(
                "00.15.09.001",
                "S",
                1,
                1,
                currentPage
        );
    }


    @Override
    public void retryPageLoad() {
        loadNextPage();
    }

    private void showErrorView(Throwable throwable) {

        if (errorLayout.getVisibility() == View.GONE) {
            errorLayout.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);

            txtError.setText(fetchErrorMessage(throwable));
        }
    }

    private String fetchErrorMessage(Throwable throwable) {
        String errorMsg = getResources().getString(R.string.error_msg_unknown);

        if (!isNetworkConnected()) {
            errorMsg = getResources().getString(R.string.error_msg_no_internet);
        } else if (throwable instanceof TimeoutException) {
            errorMsg = getResources().getString(R.string.error_msg_timeout);
        }

        return errorMsg;
    }

    private void hideErrorView() {
        if (errorLayout.getVisibility() == View.VISIBLE) {
            errorLayout.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

}

PaginationAdapter.java

public class PaginationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /* -------------------------------- View Types -------------------------------- */
    private static final int ITEM = 0;
    private static final int LOADING = 1;
    private static final String BASE_URL_IMG = "empty";

    private PaginationAdapterCallback mCallback;
    private boolean isLoadingAdded = false;
    private boolean retryPageLoad = false;
    private String errorMessage;
    private List<Result> results;
    private Context context;

    public PaginationAdapter(Context context, SickFragmentToAll fragment) {
        this.context = context;
        this.mCallback = (PaginationAdapterCallback) fragment; // The problem here
        results = new ArrayList<>();
    }

    public List<Result> getData() {
        return results;
    }

    public void setData(List<Result> results) {
        this.results = results;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType) {
            case ITEM:
                View viewItem = inflater.inflate(R.layout.item_list, parent, false);
                viewHolder = new MainItem(viewItem);
                break;
            case LOADING:
                View viewLoading = inflater.inflate(R.layout.item_progress, parent, false);
                viewHolder = new LoadingStatus(viewLoading);
                break;

        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Result result = results.get(position); // Movie

        switch (getItemViewType(position)) {


            case ITEM:
                final MainItem Item = (MainItem) holder;

                Item.ReqNo.setText(result.getReqNo());

                /* -------------------------------- Load Photo -------------------------------- */
                loadImage(result.getPhoto())
                        .listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                // TODO: 08/11/16 handle failure
                                Item.proggressBar.setVisibility(View.GONE);
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                /* -------------------------------- Image ready, Hide Proggress Now -------------------------------- */
                                Item.proggressBar.setVisibility(View.GONE);
                                return false;   // return false if you want Glide to handle everything else.
                            }
                        })
                        .into(Item.Photo);
                break;

            case LOADING:
                LoadingStatus LoadingStatus = (LoadingStatus) holder;

                if (retryPageLoad) {
                    LoadingStatus.errorLayout.setVisibility(View.VISIBLE);
                    LoadingStatus.proggressBar.setVisibility(View.GONE);

                    LoadingStatus.errorText.setText(
                            errorMessage != null ?
                                    errorMessage :
                                    context.getString(R.string.error_msg_unknown));

                } else {
                    LoadingStatus.errorLayout.setVisibility(View.GONE);
                    LoadingStatus.proggressBar.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    @Override
    public int getItemCount() {
        return results == null ? 0 : results.size();
    }

    @Override
    public int getItemViewType(int position) {
        return (position == results.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
    }

    /* -------------------------------- Helpers - bind Views -------------------------------- */

    private DrawableRequestBuilder<String> loadImage(@NonNull String posterPath) {
        return Glide
                .with(context)
                .load(BASE_URL_IMG + posterPath)
                .diskCacheStrategy(DiskCacheStrategy.ALL)   // cache both original & resized image
                .centerCrop()
                .crossFade();
    }


    /* -------------------------------- Helpers - Pagination -------------------------------- */

    public void add(Result r) {
        results.add(r);
        notifyItemInserted(results.size() - 1);
    }

    public void addAll(List<Result> moveResults) {
        for (Result result : moveResults) {
            add(result);
        }
    }

    public void remove(Result r) {
        int position = results.indexOf(r);
        if (position > -1) {
            results.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void clear() {
        isLoadingAdded = false;
        while (getItemCount() > 0) {
            remove(getItem(0));
        }
    }

    public boolean isEmpty() {
        return getItemCount() == 0;
    }

    public void addLoadingFooter() {
        isLoadingAdded = true;
        add(new Result());
    }

    public void removeLoadingFooter() {
        isLoadingAdded = false;

        int position = results.size() - 1;
        Result result = getItem(position);

        if (result != null) {
            results.remove(position);
            notifyItemRemoved(position);
        }
    }

    public Result getItem(int position) {
        return results.get(position);
    }

    /**
     * Displays Pagination retry footer view along with appropriate errorMsg
     *
     * @param show
     * @param errorMsg to display if page load fails
     */

    public void showRetry(boolean show, @Nullable String errorMsg) {
        retryPageLoad = show;
        notifyItemChanged(results.size() - 1);

        if (errorMsg != null) this.errorMessage = errorMsg;
    }


   /* -------------------------------- View Holders -------------------------------- */

    protected class MainItem extends RecyclerView.ViewHolder {
        private TextView ReqNo;
        private TextView Method;
        private TextView Name;
        private TextView Branch;
        private TextView Departement_Position;
        private TextView Type;
        private TextView Description;
        private TextView Status;
        private TextView Date;
        private TextView LeaveGroup;
        private TextView Flag;
        private TextView Code_Status;
        private ImageView Photo;
        private ProgressBar proggressBar;

        public MainItem(View itemView) {
            super(itemView);

            ReqNo = (TextView) itemView.findViewById(R.id.ReqNo);
            Method = (TextView) itemView.findViewById(R.id.Method);
            Name = (TextView) itemView.findViewById(R.id.Name);
            Branch = (TextView) itemView.findViewById(R.id.Departement_Position);
            Type = (TextView) itemView.findViewById(R.id.Type);
            Description = (TextView) itemView.findViewById(R.id.Description);
            Status = (TextView) itemView.findViewById(R.id.Status);
            Date = (TextView) itemView.findViewById(R.id.Date);
            LeaveGroup = (TextView) itemView.findViewById(R.id.LeaveGroup);
            Flag = (TextView) itemView.findViewById(R.id.Flag);
            Code_Status = (TextView) itemView.findViewById(R.id.Code_Status);

            Photo = (ImageView) itemView.findViewById(R.id.movie_poster);
            proggressBar = (ProgressBar) itemView.findViewById(R.id.movie_progress);
        }
    }


    protected class LoadingStatus extends RecyclerView.ViewHolder implements View.OnClickListener {
        private ProgressBar proggressBar;
        private ImageButton retryButton;
        private TextView errorText;
        private LinearLayout errorLayout;

        public LoadingStatus(View itemView) {
            super(itemView);

            proggressBar = (ProgressBar) itemView.findViewById(R.id.loadmore_progress);
            retryButton = (ImageButton) itemView.findViewById(R.id.loadmore_retry);
            errorText = (TextView) itemView.findViewById(R.id.loadmore_errortxt);
            errorLayout = (LinearLayout) itemView.findViewById(R.id.loadmore_errorlayout);

            errorText.setOnClickListener(this);
            errorLayout.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.loadmore_retry:
                case R.id.loadmore_errorlayout:

                    showRetry(false, null);
                    mCallback.retryPageLoad();

                    break;
            }
        }
    }

}

我想让 PaginationAdapter 动态化,.知道如何到达它吗?

最佳答案

希望对您有所帮助。

假设 PaginationAdapterCallback 是这样的

public interface PaginationAdapterCallback{
 void loadNextPage(); 
 void retryPageLoad();
 void loadFirstPage();
}

创建一个父类 SickFragment 实现 PaginationAdapterCallback

public abstract SickFragment implements PaginationAdapterCallback{
}

创建子类。

SickFragmentToCanceled extends SickFragment
SickFragmentToAll extends SickFragment

现在使用下面的构造函数创建PaginationAdapter

PaginationAdapter(Context context, SickFragment fragment)

您会找到所有需要的方法。

关于java - 如何动态创建类 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46338068/

相关文章:

java - Libgdx 事件非循环动画的起始帧

java - 如何将两个列表项结果显示为一个,以获得多个结果。在 selenium Webdriver 中使用 java

java - Thymeleaf 3.0 模板引擎,从两个位置获取模板

java - 背景图像重复+圆角

java - com.google.firebase.database.DatabaseException : Expected a Map while deserializing, 但得到了一个类 java.lang.Long

即使设置了lifecycleOwner,Android Fragment ViewModel数据绑定(bind)也不会更新UI

android - Titanium Android 屏幕方向

android - 为什么我的 Android 应用程序显示空白然后崩溃?

java - fragment 无法正常工作

android - 在 fragment 中单击按钮后填充 ListView