为每个项目添加Onclick on适配器以打开新的不同活动

时间:2018-08-27 10:38:01

标签: java android android-recyclerview adapter

我的项目中有适配器,有几个片段,其中用名人姓名和出生日期填充片段,如下图所示 enter image description here

我想为每个项目调用不同的网址

对于第一项

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));

第二项

startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(“ http://www.youtube.com”))));

以此类推

下面是我的适配器类

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<Model> mDataset;
    private ImageLoader mImageLoader;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView nameText;
        public TextView phoneText;
        public NetworkImageView image;
        @SuppressLint("WrongViewCast")
        public ViewHolder(View v) {
            super(v);
            nameText = v.findViewById(R.id.name_text);
            phoneText = v.findViewById(R.id.phone_text);
            image = v.findViewById(R.id.imgAvatar);
            image.setDefaultImageResId(R.mipmap.ic_launcher);
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(),"Position: "+getAdapterPosition(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(List<Model> myDataset, Context mCOntext) {
        Log.d("TEST",myDataset.get(0).getName());
        mDataset = myDataset;
        mImageLoader = MySingleton.getInstance(mCOntext).getImageLoader();
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view, parent, false);
        // set the view's size, margins, paddings and layout parameters

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        //holder.mTextView.setText(mDataset.get(position).getName());
        Log.d("TEST","Printing Names onBindView Holder"+mDataset.get(position).getName());
        holder.nameText.setText(mDataset.get(position).getName());
        holder.phoneText.setText(mDataset.get(position).getPhone());
        holder.image.setImageUrl(mDataset.get(position).getImage(),mImageLoader);

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }
}

我的片段是

public class english extends Fragment implements Response.Listener , Response.ErrorListener {

    View view;
    RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private Context context;
    private List<Model> contactList  = new ArrayList<>();
    private String url ="https://api.androidhive.info/json/contacts.json";
    Button btn;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragment,container,false);
        context = getContext();
        mLayoutManager = new GridLayoutManager(context,2);
        mRecyclerView = (RecyclerView)view.findViewById(R.id.my_recycler_view);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        getContactList();
        return view;
    }

    private void getContactList(){
        Log.d("TEST","Getting Contact list");
        Controller.getInstance(context).makeNetworkCalls(Request.Method.GET,url,this,this);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Error: " + error.getMessage());
        Toast.makeText(context, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResponse(Object response) {
        Log.d("TEST","Got The response" +response);
        if (response == null) {
            Toast.makeText(context, "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
            return;
        }

        List<Model> items = new Gson().fromJson(response.toString(), new TypeToken<List<Model>>(){}.getType());
        contactList.addAll(items);
        MyAdapter rcAdapter = new MyAdapter(contactList,context);
        mRecyclerView.setAdapter(rcAdapter);
    }
}

请帮助。

2 个答案:

答案 0 :(得分:1)

简单

首先创建URL数组 在适配器类中

ArrayList<String> UrlsToTran=new ArrayList<>();

在适配器类构造器中

MyAdapter(Context mContext)
{
  //Assing Context 
  //Assign The Urls
    UrlsToTran.add("www.stackoverflow.com");
    UrlsToTran.add("www.facebook.com");
    //And Add More Values As U need

}

然后添加OnClick监听器

public void onBindViewHolder(ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    //holder.mTextView.setText(mDataset.get(position).getName());
    Log.d("TEST","Printing Names onBindView 
     Holder"+mDataset.get(position).getName());
    holder.nameText.setText(mDataset.get(position).getName());
    holder.phoneText.setText(mDataset.get(position).getPhone());
    holder.image.setImageUrl(mDataset.get(position).getImage(),mImageLoader);

    holder.image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) 
{
     context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(UrlsToTran.get(position).toString())));

}
    });

}

答案 1 :(得分:0)

首先,为适配器中的每个项目创建一个OnClickListener,如下所示:

    holder.image.setOnClickListener(v->{

    });

现在在适配器和显示列表的片段/活动之间创建接口

 public interface ModelListener {
        void onModelClicked(Model model);
}

在您的活动/片段中,听某项单击并发送意图

new ModelListener(){

   public void onModelClicked(Model model){
       startActivity(new Intent(.., model.getUrl()));
   }
}