如何在片段和适配器之间创建接口

时间:2018-01-16 05:44:28

标签: android android-fragments android-adapter

我已经能够在适配器中创建一个接口来与片段进行通信。

这是适配器代码

public class AgroInfoAdapter extends RecyclerView.Adapter<AgroInfoAdapter.ViewHolder> {
private Context mContext;
ArrayList<JsonObject> extensionItem = new ArrayList<>();
public Typeface tf;


public AgroInfoAdapter.AgroInfoAdapterListener listener;

public AgroInfoAdapter(Context context, ArrayList<JsonObject> extensionItem) {
    this.extensionItem = extensionItem;
    this.mContext = context;
    this.tf = Typeface.createFromAsset(context.getAssets(), "FiraSans-Light.ttf");
}

@Override
public AgroInfoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_crop_info, null);
    AgroInfoAdapter.ViewHolder viewHolder = new AgroInfoAdapter.ViewHolder(itemLayoutView);
    return viewHolder;

}

public static class ViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.header)
    public TextView header;
    @BindView(R.id.body)
    public TextView body;
    @BindView(R.id.thumbnail)
    public ImageView thumbnail;

    @BindView(R.id.button)
    public Button button;


    @BindView(R.id.downloadProgressView)
    DownloadProgressView downloadProgressView;

    @BindView(R.id.row)
    public LinearLayout row;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        ButterKnife.bind(this, itemLayoutView);
    }
}

@Override
public void onBindViewHolder(AgroInfoAdapter.ViewHolder viewHolder, final int position) {


    try {
        JsonObject sl = extensionItem.get(position);
        viewHolder.header.setText(sl.get("title").getAsString());
        if ((sl.get("title").getAsString()).equals("Land preparation")) {

            viewHolder.button.setVisibility(View.VISIBLE);
        }
        Glide.with(mContext).load(CONFIG.IMAGE_URL+ sl.get("photo_url").getAsString())
                .thumbnail(0.5f)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .fallback(R.drawable.fallback)
                        .placeholder(R.drawable.progress_animation)
                        .error(R.drawable.fallback)
                )
                .into(viewHolder.thumbnail);
        String description="";
        for (JsonElement e:sl.get("description").getAsJsonArray()){
            if(!e.getAsString().trim().isEmpty() && CharMatcher.javaUpperCase().or(CharMatcher.javaLetter().negate()).matchesAllOf(e.getAsString().trim())) {
                SpannableString s1 = new SpannableString(e.getAsString());
                s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
                description +=s1 + "\n\n";

            }else if(!e.getAsString().trim().isEmpty()) {
                SpannableString s1 = new SpannableString(e.getAsString());
                s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
                description +=s1 + "\n\n";;
                viewHolder.body.setText(description);
                viewHolder.body.setTypeface(tf);

            }

        }




    } catch (Exception e) {
    }

    applyClickEvents(viewHolder, position);

}

public interface AgroInfoAdapterListener {

    void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);

}

private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            listener.onCartRowClicked(view, holder.downloadProgressView, position);
        }
    });
}




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

}

这是我连接到适配器的光环

AgroInfoAdapter adapter;

@BindView(R.id.rv)
RelativeLayout _RecyclerViewLayout;
@BindView(R.id.empty_rv)
RelativeLayout _EmptyRecyclerViewLayout;
@BindView(R.id.recycler_desc)
RecyclerView recyclerView;

Toolbar mToolbar;
@BindView(R.id.progress_bar)
ProgressBar progressBar;

@BindView(R.id.rv_layout) RelativeLayout relativeLayout;

ArrayList<JsonObject> ins = new ArrayList<>();

AgroInfoActivity.OnCropperSpinnerSelectedListener listener;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    listener = new AgroInfoActivity.OnCropperSpinnerSelectedListener() {
        @Override
        public void onItemSelected(String pos) {
            new LongOperation().execute(pos);
        }
    };

    ((AgroInfoActivity)getActivity()).addCropperSpinnerSelectedListener(listener);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_ext_land, container, false);
    ButterKnife.bind(this,view);
    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    adapter = new AgroInfoAdapter(getActivity(), ins);
    recyclerView.setAdapter(adapter);
    return view;
}

@Override
public void onResume() {

    new LongOperation().execute(((AgroInfoActivity)getActivity()).cropsSpinner.getSelectedItem().toString());
    super.onResume();
}
private class LongOperation extends AsyncTask<String, Void, ArrayList<JsonObject>> {

    @Override
    protected ArrayList<JsonObject> doInBackground(String... params) {
        try {
            couchdbCropInfo = new CouchdbCropInfo(getActivity());
            return couchdbCropInfo.allCropInfo(params[0],TYPE);
        } catch (CouchbaseLiteException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<JsonObject> result) {
        ins.addAll(result);
        adapter.notifyDataSetChanged();
        if (ins.isEmpty()) {
            _RecyclerViewLayout.setVisibility(View.GONE);
            _EmptyRecyclerViewLayout.setVisibility(View.VISIBLE);
        } else {
            _RecyclerViewLayout.setVisibility(View.VISIBLE);
            _EmptyRecyclerViewLayout.setVisibility(View.GONE);
        }
        relativeLayout.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onPreExecute() {
        relativeLayout.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
        ins.clear();
    }

    @Override
    protected void onProgressUpdate(Void... values) {}
}



@Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {

    Bundle bundle = new Bundle();
        FragmentTransaction fragmentTransaction = getActivity()
                .getFragmentManager()
                .beginTransaction();
        Fragment fragmentB = new PostFragment();
        fragmentB.setArguments(bundle);
        fragmentTransaction.replace(R.id.parent, fragmentB);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

}

}

基本上我想要实现的是我想在单击按钮时调用片段。该活动是一个包含大约5个片段的tablaout。 当我点击按钮。是什么带来了这个以及如何最好地解决它或者可以做到这一点?提前谢谢。

1 个答案:

答案 0 :(得分:1)

在声明适配器的位置或适配器的构造函数中,启动侦听器。

在片段方面,

class Test extends Fragment {
AdapterClass adapter = new AdapterClass();
adapter.setListner(..)
view.setAdapter(adapter);


@Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {

}
}

在Adapter类

class AdapterClass {

private AgroInfoAdapterListener listner;

public setListner(AgroInfoAdapterListener listner) {
this.listner = listner;
}


public interface AgroInfoAdapterListener {

    void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);

}

private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}

}