0
我想將OnClickListener
添加到RecyclerView
項目。我正在使用AsyncTask
從互聯網上獲取數據並將該數據加載到RecyclerView
項目中。之前我使用字符串數組向RecyclerView
添加數據,它工作正常。但是現在我在AsyncTask
活動中創建RecyclerView
適配器。我想在MainActivity
內執行itemclicked
方法來執行。但它現在不執行。如何在AsyncTask中的RecyclerView項目上設置OnClickListener
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();
}
}
}
我的適配器類是這個樣子
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);
}
}
Thanks denis_lor – user2297998