简体   繁体   English

如何在AsyncTask中的RecyclerView项上设置OnClickListener

[英]How to set OnClickListener on RecyclerView items inside AsyncTask

I want to add OnClickListener to RecyclerView items. 我想将OnClickListener添加到RecyclerView项目。 I am using AsyncTask to get data from internet and load that data into RecyclerView items. 我正在使用AsyncTask从互联网获取数据并将该数据加载到RecyclerView项目中。 Earlier I was using string array to add data to RecyclerView , it was working fine. 早些时候,我使用字符串数组将数据添加到RecyclerView ,但工作正常。 But now I am creating RecyclerView adapter inside AsyncTask activity. 但是现在我正在AsyncTask活动中创建RecyclerView适配器。 I want to execute itemclicked method inside MainActivity to be executed. 我想在MainActivity执行itemclicked方法来执行。 But it is not executed right now. 但是它现在不执行。

package com.example.rahul.navigationdrawer;
public class MainActivity extends AppCompatActivity implements addapter.ClickListener{

    //Defining Variables
    public ProgressDialog mProgressDialog;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private Toolbar toolbar;
    public RecyclerView mRecyclerView;
    public RecyclerView.LayoutManager mLayoutManager;

    public addapter adpt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        ParseObject testObject = new ParseObject("TestObject");
        testObject.put("foo", "bar");
        testObject.saveInBackground();
        setContentView(R.layout.activity_main);
        setupToolbar();
        setupCollapsingToolbarLayout();


     // HttpParseResponse httpParseResponse=new HttpParseResponse(MainActivity.this);
      //httpParseResponse.execute();

        HttpParseRequest httpParseRequest=new HttpParseRequest(MainActivity.this);
        httpParseRequest.execute();
        // Initializing Toolbar and setting it as the actionbar
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        if (collapsingToolbarLayout != null) {
            collapsingToolbarLayout.setTitle(toolbar.getTitle());}
            //Initializing NavigationView
            navigationView = (NavigationView) findViewById(R.id.navigation_view);

        SntpClient client = new SntpClient();
        if (client.requestTime("0.us.pool.ntp.org",60000)) {
            long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();

            Toast.makeText(MainActivity.this, "Its our Time" + now, Toast.LENGTH_LONG);
            System.out.print(now);
        }

            //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

                // This method will trigger on item Click of navigation menu
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {


                    //Checking if the item is in checked state or not, if not make it in checked state
                    if (menuItem.isChecked()) menuItem.setChecked(false);
                    else menuItem.setChecked(true);

                    //Closing drawer on item click
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          drawerLayout.closeDrawers();

                    //Check to see which item was being clicked and perform appropriate action
                    switch (menuItem.getItemId()) {

                      //Replacing the main content with ContentFragment Which is our Inbox View;
                        case R.id.Profile:
                           startActivity(new Intent(MainActivity.this,My_Location.class));
                            return true;

                        // For rest of the options we just show a toast on click

                        case R.id.RideNow:
                            Toast.makeText(getApplicationContext(), "your device id is"+id, Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.History:
                            Toast.makeText(getApplicationContext(), "History", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.FreeRide:
                            Toast.makeText(getApplicationContext(), "Free Ride", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.PaymentPayTM:
                            Toast.makeText(getApplicationContext(), "Payment/PayTM", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.FavoritePickupLocations:
                            Toast.makeText(getApplicationContext(), "Favorite Pickup Locations", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.Unlockroute:
                            Toast.makeText(getApplicationContext(), "Unlock Route", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.Help:
                            Toast.makeText(getApplicationContext(), "Help", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.About:
                            Toast.makeText(getApplicationContext(), "About", Toast.LENGTH_SHORT).show();
                            return true;
                        case R.id.Contactus:
                            Toast.makeText(getApplicationContext(), "Contact Us", Toast.LENGTH_SHORT).show();
                            return true;
                        default:
                            Toast.makeText(getApplicationContext(), "Select Right Option ", Toast.LENGTH_SHORT).show();
                            return true;

                    }
                }
            });

            // Initializing Drawer Layout and ActionBarToggle
            drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
            ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {

                @Override
                public void onDrawerClosed(View drawerView) {
                    // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                    super.onDrawerClosed(drawerView);
                }

                @Override
                public void onDrawerOpened(View drawerView) {
                    // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                    super.onDrawerOpened(drawerView);
                }
            };


            //Setting the actionbarToggle to drawer layout
            drawerLayout.setDrawerListener(actionBarDrawerToggle);

            //calling sync state is necessay or else your hamburger icon wont show up
            actionBarDrawerToggle.syncState();



    }
    private void setupToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if(toolbar != null)
            setSupportActionBar(toolbar);

        // Show menu icon
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);

    }
    private void setupCollapsingToolbarLayout(){

        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        if(collapsingToolbarLayout != null){
            collapsingToolbarLayout.setTitle(toolbar.getTitle());
            collapsingToolbarLayout.setCollapsedTitleTextColor(0xED1C24);
            collapsingToolbarLayout.setExpandedTitleColor(0xED1C24);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void itemClicked(View view, int position) {
        Toast.makeText(MainActivity.this,"rahul kumar",Toast.LENGTH_LONG).show();

        final TextView textView=(TextView)view.findViewById(R.id.text);
        String string=textView.getText().toString();

        Intent intent=new Intent(getApplicationContext(), subactivity.class);
        intent.putExtra("Pickuplocation", string);
        intent.putExtra("LayoutPosition", position);
        startActivity(intent);

    }

    public class HttpParseRequest extends AsyncTask<Void,String,List<data>> implements addapter.ClickListener{

        Context context;
        Boolean x;
        public HttpParseRequest(MainActivity mainActivity) {

        }
        HttpURLConnection urlConnection;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);

            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }
        @Override
        protected List<data> doInBackground(Void... params) {

            JSONObject object=postData();
            List<data> dataList1 = null;
            try {
                dataList1 = getdata(object);
                adpt =new addapter(MainActivity.this,dataList1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

          //  x= sendotp();
            return dataList1;
        }
        @Override
        protected void onPostExecute(List<data> list) {
            super.onPostExecute(list);

            mRecyclerView = (RecyclerView) findViewById(R.id.listview);
            mRecyclerView.setHasFixedSize(true);
            // use a linear layout manager
            mLayoutManager = new LinearLayoutManager(context);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setAdapter(adpt);
            mProgressDialog.dismiss();

        }
        public List<data> getdata(JSONObject jsonObject) throws JSONException {
            List<data> dataList=new ArrayList<>();
            JSONArray jsonArray=jsonObject.getJSONArray("result");

               if(jsonObject==null)
               {
                   Log.d("Kumar---","*********************---------------------------------");
               }
                int icons[]={R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu,R.drawable.ic_menu};
                String [] strings={"U15/Road","U10/Road","U2/Road","Yadav Properties"};
                for(int i=0;i<icons.length && i<jsonArray.length();i++)
                {

                    data d=new data();
                    d.i=icons[i];
                  //  d.id=jsonArray.getJSONObject(i).getString("id");
                    d.string=jsonArray.getJSONObject(i).getString("name");
                   // d.routeid=jsonArray.getJSONObject(i).getJSONObject("route").getString("objectId");
                    dataList.add(d);
                }
            return dataList;
        }
        @Override
        public void itemClicked(View view, int position) {
            Toast.makeText(MainActivity.this,"Rahul",Toast.LENGTH_LONG).show();
        }
    }
    }

My adapter class is look like this 我的适配器类看起来像这样

public class addapter extends RecyclerView.Adapter<addapter.MyViewHolder>{
List<data> datalist= Collections.emptyList();
private LayoutInflater inflater;
private Context context;

public addapter(Context mainActivity, List<data> datalist)
{

    this.context=mainActivity;
    inflater = LayoutInflater.from(context);
    this.datalist=datalist;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {


   View view= inflater.inflate(R.layout.cardviews, parent, false);
    MyViewHolder holder=new MyViewHolder(view);
    holder.textView.setTag(holder);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    data dls = datalist.get(position);
    holder.textView.setText(dls.string);
    holder.imageView.setImageResource(dls.i);
    holder.setClickListener(new ClickListener() {
        @Override
        public void itemClicked(View view, int position) {

        }
    });

}
@Override
public int getItemCount() {

    return datalist.size();
}

  public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView textView;
    ImageView imageView;
  public ClickListener clickListener;
    public MyViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        textView=(TextView)itemView.findViewById(R.id.text);
        textView.setTextColor(Color.rgb(255, 110, 155));

        imageView=(ImageView)itemView.findViewById(R.id.image);
    }
  public void setClickListener(ClickListener clickListener)
  {
      this.clickListener=clickListener;
  }
    @Override
    public void onClick(View v) {
        if(clickListener!=null)
        {
            clickListener.itemClicked(v,this.getLayoutPosition());
        }


    }
}
public interface ClickListener{
    void itemClicked(View view, int position);

}
}

1) create OnItemClick.java interface: 1)创建OnItemClick.java接口:

 public interface OnItemClick {

    void onClickItem (View caller, int position);

 }

2) In your MainActivity implements OnItemClick and add this parameter to your constructor call in doInBackground: 2)在您的MainActivity中实现OnItemClick并将this参数添加到doInBackground中的构造函数调用中:

adpt =new addapter(MainActivity.this,dataList1, this);

3) You should separate ViewHolder and Adapter classes. 3)您应该将ViewHolderAdapter类分开。 Anyway in your ViewHolder class: 无论如何,在您的ViewHolder类中:

implements View.OnClickListener , then define your ViewHolder like this: 实现View.OnClickListener ,然后像这样定义您的ViewHolder

private OnItemClick mListener;

public ListViewHolder(View view, OnItemClick listener) {
        super(view);
        this.mListener = listener;
        view.setOnClickListener(this);
    }

@Override
public void onClick(View view) {
    mListener.onClickItem(view, getAdapterPosition());
}

4) in your adapter class: 4)在您的适配器类中:

private OnItemClick mListener;

public addapter(Context mainActivity, List<data> datalist, OnItemClick listener)
{
    this.mListener = listener;
    this.context=mainActivity;
    inflater = LayoutInflater.from(context);
    this.datalist=datalist;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view= inflater.inflate(R.layout.cardviews, parent, false);
    MyViewHolder holder=new MyViewHolder(view, mListener);
    holder.textView.setTag(holder);
    return holder;
}

5) and in your MainActivity: 5)并在您的MainActivity中:

 @Override
    public void onClickItem(View caller, int position) {
            Toast.makeText(MainActivity.this,"Rahul",Toast.LENGTH_LONG).show();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM