如何创建动态类Java

时间:2017-09-21 07:36:46

标签: java android android-fragments

我在 Android 中遇到了Java class的问题,在此我想为某些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);

PaginationAdapter **

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充满活力,。知道怎么去达吗?

3 个答案:

答案 0 :(得分:1)

希望这会对你有所帮助。

让我们说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)

您将找到所需的所有方法。

答案 1 :(得分:0)

我已经体验过它并将其替换为thisContext

尝试替换

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

thisContext = container.getContext();
adapter = new PaginationAdapter(thisContext);

首先在班级thisContext

中声明Context thisContext

我希望它有效

答案 2 :(得分:0)

我尝试替换 adapter = new PaginationAdapter(getActivity(), fragment);adapter = new PaginationAdapter(getActivity());这对我有用,你试过替换吗?