How do I get two textviews from recycler view in email intent? - android

As you can see looking at some parts of my code I'm very new to Android and Java, but as bad as the code looks to the pro guys, it’s doing what I want it to do so far (I’m sure I’ll get there…lol). I have a custom adapter with a recycler view. There are some text views. I also have a bottom menu with an email button and I would like to use 2 of the views (R.id.brand_name & R.id.cases_text_view) and sent them as text in an email intent. The bottom menu and the email intent is working where it is, but I don’t how to call the two text views into the EXTRA_TEXT. Please help me out.
Just one more thing: thank you to all you guys, I wouldn't have been so far with this app if it weren't for this website and all your help. I really appreciate it.
Here is the class with the bottom menu and email intent:
public class BlackLabel extends brands {
private RecyclerView recyclerView;
//private String modelArrayList;
//private Context ctx;
public static ArrayList<Model> modelArrayList;
private CustomAdapter customAdapter;
//private Button btnnext;
// supossing to have an image called ic_play inside my drawables.
public String[] brandlist = new String[]{
"Black Label 340ml NRB (85023)",
"Black Label 330ml Cans (85736)",
"Black label 500ml Cans (85023)",
"Black Label 440ml NRB (86798)",
"Black Label 330ml RB (85556)",
"Black Label 750ml RB (85021)",
"Black Label 340ml NRB 12 Pack (87009)",
"Black Label 500ml Cans 12 Pack (85022)"};
public int[] pallet_size = {
84,
127,
81,
80,
120,
70,
132,
90};
public int[] myimage = {
R.drawable.black_label,
R.drawable.brutal_fruit,
R.drawable.castle_lager,
R.drawable.flying_fish,
R.drawable.castle_lite,
R.drawable.hansa,
R.drawable.lion_lager,
R.drawable.milk_stout};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order_by_brand);
setTitle("Black Label");
recyclerView = (RecyclerView) findViewById(R.id.recycler);
modelArrayList = getModel();
customAdapter = new CustomAdapter(this);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}
private ArrayList<Model> getModel() {
final ArrayList<Model> list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
final Model model = new Model();
model.setNumber(0);
model.setNumber2(0);
model.setImage(myimage[i]);
model.setBrand(brandlist[i]);
model.setPallet_size(pallet_size[i]);
list.add(model);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavView_Bar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(0);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
Intent intent1 = new Intent(BlackLabel.this, MainActivity.class);
startActivity(intent1);
break;
case R.id.ic_clear:
Intent intent2 = new Intent(BlackLabel.this, BlackLabel.class);
startActivity(intent2);
break;
case R.id.ic_email:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:who#where.co.za"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Please place order for....");
intent.putExtra(Intent.EXTRA_TEXT, "Here I want some text from the adapter.");
startActivity(intent);
}
return false;
}
});
}
return list;
}}
And here is my Custom Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Context ctx;
public CustomAdapter(Context ctx) {
inflater = LayoutInflater.from(ctx);
this.ctx = ctx;
}
#Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, int position) {
holder.tvBrand.setText((CharSequence) modelArrayList.get(position).getBrand());
holder.tvImage.setImageResource(Integer.parseInt(String.valueOf(modelArrayList.get(position).getImage())));
holder.tvCases.setText(String.valueOf(modelArrayList.get(position).getNumber()));
holder.tvPallet_size.setText(String.valueOf(modelArrayList.get(position).getPallet_size()));
holder.tvCases.setText(String.valueOf(modelArrayList.get(position).getNumber2()));
holder.tvPallets.setText(String.valueOf(modelArrayList.get(position).getNumber()));
holder.tvCases.setText(String.valueOf(modelArrayList.get(position).getNumber2()));
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected Button btn_cases_plus, btn_cases_minus, btn_pallets_plus, btn_pallets_minus;
protected ImageView tvImage;
private TextView tvBrand, tvCases,tvPallets, tvPallet_size;
public MyViewHolder(View itemView) {
super(itemView);
tvBrand = (TextView) itemView.findViewById(R.id.brand_name);
tvImage = (ImageView) itemView.findViewById(R.id.beer_logo);
tvCases = (TextView) itemView.findViewById(R.id.cases_text_view);
tvPallet_size = (TextView) itemView.findViewById(R.id.pallets_size);
tvPallets = (TextView) itemView.findViewById(R.id.pallets_text_view);
btn_cases_plus = (Button) itemView.findViewById(R.id.casePlus1);
btn_cases_minus = (Button) itemView.findViewById(R.id.caseMinus1);
btn_pallets_plus = (Button) itemView.findViewById(R.id.palletsPlus1);
btn_pallets_minus = (Button) itemView.findViewById(R.id.palletsMinus1);
btn_cases_plus.setTag(R.integer.btn_cases_plus_view, itemView);
btn_cases_minus.setTag(R.integer.btn_cases_minus_view, itemView);
btn_cases_plus.setOnClickListener(this);
btn_cases_minus.setOnClickListener(this);
btn_pallets_plus.setTag(R.integer.btn_pallets_plus_view, itemView);
btn_pallets_minus.setTag(R.integer.btn_pallets_minus_view, itemView);
btn_pallets_plus.setOnClickListener(this);
btn_pallets_minus.setOnClickListener(this);
}
// onClick Listener for view
#Override
public void onClick(View v) {
if (v.getId() == btn_cases_plus.getId()){
View tempview = (View) btn_cases_plus.getTag(R.integer.btn_cases_plus_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
int number = Integer.parseInt(tvCases.getText().toString()) + 1;
tvCases.setText(String.valueOf(number));
modelArrayList.get(getAdapterPosition()).setNumber(number);
} else if(v.getId() == btn_cases_minus.getId()) {
View tempview = (View) btn_cases_minus.getTag(R.integer.btn_cases_minus_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
int number = Integer.parseInt(tvCases.getText().toString()) - 1;
if (number == 0 || number <0) {
Toast.makeText(ctx,"You cannot order less than one case", Toast.LENGTH_SHORT).show();
tvCases.setText(String.valueOf(0));
return;
}
tvCases.setText(String.valueOf(number));
modelArrayList.get(getAdapterPosition()).setNumber(number);
} else if(v.getId() == btn_pallets_plus.getId()) {
View tempview = (View) btn_pallets_plus.getTag(R.integer.btn_pallets_plus_view);
TextView tvPallets = (TextView) tempview.findViewById(R.id.pallets_text_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
TextView tvPallet_size = (TextView) tempview.findViewById(R.id.pallets_size);
int number = Integer.parseInt(tvPallets.getText().toString()) + 1;
tvPallets.setText(String.valueOf(number));
int number2 = Integer.parseInt(tvPallets.getText().toString()) * Integer.parseInt(tvPallet_size.getText().toString());
tvCases.setText(String.valueOf(number2));
modelArrayList.get(getAdapterPosition()).setNumber(number);
modelArrayList.get(getAdapterPosition()).setNumber2(number2);
} else if(v.getId() == btn_pallets_minus.getId()) {
View tempview = (View) btn_pallets_minus.getTag(R.integer.btn_pallets_minus_view);
TextView tvPallets = (TextView) tempview.findViewById(R.id.pallets_text_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
TextView tvPallet_size = (TextView) tempview.findViewById(R.id.pallets_size);
int number = Integer.parseInt(tvPallets.getText().toString()) - 1;
tvPallets.setText(String.valueOf(number));
int number2 = Integer.parseInt(tvPallets.getText().toString()) * Integer.parseInt(tvPallet_size.getText().toString());
tvCases.setText(String.valueOf(number2));
if (number == 0 || number <0) {
Toast.makeText(ctx,"You cannot order less than one pallet", Toast.LENGTH_SHORT).show();
tvCases.setText(String.valueOf(0));
tvPallets.setText(String.valueOf(0));
}
modelArrayList.get(getAdapterPosition()).setNumber(number);
modelArrayList.get(getAdapterPosition()).setNumber2(number2);
}
}
}
}

Here is your code
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:who#where.co.za"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Please place order for....");
intent.putExtra(Intent.EXTRA_TEXT, "Here I want some text from the adapter.");
startActivity(intent);
Try to make next thing. Firstly, I don't really know why you didn't finish loop after this part of code but ok let's work with it.
private ArrayList<Model> getModel() {
final ArrayList<Model> list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
final Model model = new Model();
model.setNumber(0);
model.setNumber2(0);
model.setImage(myimage[i]);
model.setBrand(brandlist[i]);
model.setPallet_size(pallet_size[i]);
list.add(model);
So here in every iteration of loop you got model object which you setting properties. So you could get data just from the model like model.getBrand(). I don't know what is "cases"(R.id.cases_text_view) in you app but i think it's set here
model.setNumber(0);
model.setNumber2(0);
So just get this number like
model.getNumber(); model.getNumber2(0);
So what is in the end:
You should make 3 "get" methods for your model class returning "String" type
getBrand()
getNumber()
getNumber2()
Then just add next code:
Intent intent = new Intent(Intent.ACTION_SENDTO);
String extraData = model.getBrand() + getNumber() getNumber2();
intent.setData(Uri.parse("mailto:who#where.co.za"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Please place order for....");
intent.putExtra(Intent.EXTRA_TEXT, extraData);
startActivity(intent);
Hope it would help you! ask if anything.

If you want to pass those two values of views to the main activity
1. Create a method with 2 parameters in your activity
2. Set click listener on your list and onClick just call that method of your recycle view with view parameters.Inside your onClick method write
((your_activity_name)context).methodName(parameters here);
Hope this will help you
Thanks!!!

Related

Android retrofit recycleviw item onclicklistener call other api

I have a recycle view that contain information from API
After that in every item of the recycleview i have button that open new activity
This newactivity call a second API and have query parameter as an information from the first API
My problem is how to use an information from the firstactivity in my adapter directly because i have the new intent (that will open the secondactivity and in the same time send the variable to the secondactivity) in the adapter
class ItemViewHolder extends RecyclerView.ViewHolder{
public TextView code,description,emplacement;
public ImageButton fils,detailsactif,serviceId;
public ItemViewHolder(View itemView) {
super(itemView);
code= (TextView) itemView.findViewById(R.id.txtcode);
description= (TextView) itemView.findViewById(R.id.txtdescription);
emplacement= (TextView) itemView.findViewById(R.id.txtemplacement);
fils= (ImageButton) itemView.findViewById(R.id.fils);
detailsactif= (ImageButton) itemView.findViewById(R.id.detailsactif);
serviceId= (ImageButton) itemView.findViewById(R.id.serviceId);
itemView.findViewById(R.id.detailsactif).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View itemView) {
Intent intent = new Intent(itemView.getContext(), details_actif.class);
intent.putExtra("asset","zz");
(itemView.getContext()).startActivity(intent);
}
});
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ItemViewHolder)
{
Item item = items.get(position);
String codeAsset = item.getCode();
ItemViewHolder viewHolder = (ItemViewHolder) holder;
viewHolder.code.setText(items.get(position).getCode());
viewHolder.description.setText(items.get(position).getDescription());
viewHolder.emplacement.setText(items.get(position).getEmplacement());
// viewHolder.detailsactif.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View itemView) {
// Intent intent = new Intent(itemView.getContext(), details_actif.class);
// (itemView.getContext()).startActivity(intent);
//
// }
// });
---------------firstactivity---------------------
Call<Modal> userList = ApiClient.getUserService().getData();
userList.enqueue(new Callback<Modal>() {
#Override
public void onResponse(Call<Modal> call, Response<Modal> response) {
if(response.isSuccessful()) {
List<UserResponse> userResponses = (response.body()).getmUsersResponse();
for (int i=0; i<10; i++)
{
// SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
// SharedPreferences.Editor editor = mPreferences.edit();
// String code2 = mPreferences.getString(getString(R.string.code),"");
// setText(code2);
String code = userResponses.get(i).getAssetnum();
String description = userResponses.get(i).getDescription();
String emplacement = userResponses.get(i).getSiteid();
ImageButton fils= (ImageButton) view.findViewById(R.id.fils);
ImageButton details_actif= (ImageButton) view.findViewById(R.id.detailsactif);
ImageButton serviceId = (ImageButton) view.findViewById(R.id.serviceId);
//
Item item = new Item(code,description,emplacement,fils,details_actif,serviceId);
items.add(item);
}
// Log.e("sucess",(response.body()).getmUsersResponse().toString());
RecyclerView listeactif = (RecyclerView) view.findViewById(R.id.listeactif);
listeactif.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new MyAdapter(listeactif, getActivity(), items);
listeactif.setAdapter(adapter);
Save query parameter for the second API from first API as model in recyclerview. While clicking the recyclerview Holder pass the value from model to new activity as intent.put(YourValue). From the new activity read the intent and call second API
Save first API result as a list --> Make Recyclerview with list --> Pass model value to new Activity when clicking the button in holder.

Send the random color of the card item to onClick

I have RecyclerView + card. In the card, one element must be of a random color.
I created an array of colors and implemented the task in this way -
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.model_poem, parent, false);
int[] androidColors = view.getResources().getIntArray(R.array.androidColors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
if (frameLayout != null) {
frameLayout.setBackgroundColor(randomAndroidColor);
}
return new ViewHolder(view);
}
When you click on a card, the activaty with full information opens and the color of the toolbar must coincide the color of the element in the card.
public ViewHolder(View itemView) {
super(itemView);
titleTv = (TextView) itemView.findViewById(R.id.tv_title);
..............
frameLayout = (FrameLayout) itemView.findViewById(R.id.frame_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ReadActivity.class);
long poemId = (Long) v.getTag();
intent.putExtra("randomAndroidColor", frameLayout.getBackground().toString());
onPoemClickListener.onPoemClick(poemId);
}
});
}
}
public interface OnPoemClickListener {
void onPoemClick(long poemId);
}
class activity
public class ReadActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
public static final String EXTRA_POEM_ID = "poem_id";
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv_Title = (TextView) findViewById(R.id.tv_title);
.......
Intent intent = getIntent();
randomAndroidColor = intent.getStringExtra("randomAndroidColor");
toolbar.setBackgroundColor(Integer.parseInt(randomAndroidColor));
poemId = getIntent().getLongExtra(EXTRA_POEM_ID, -1);
if (poemId == -1) {
finish();
}
getSupportLoaderManager().initLoader(
0,
null,
this
);
}
Application crashes with error E/AndroidRuntime: FATAL EXCEPTION: main
Process: rodionova.lyubov.brodsky, PID: 31328
java.lang.RuntimeException: Unable to start activity ComponentInfo{rodionova.lyubov.brodsky/rodionova.lyubov.brodsky.activity.ReadActivity}: java.lang.NumberFormatException: s == null
In this case, I think the easiest thing to do would be to save the color int as the FrameLayout's tag, and then retrieve the tag when you want to pass it to the activity. This way you don't have to worry about handling the background drawable and/or converting it to a color.
Set the tag:
int[] androidColors = view.getResources().getIntArray(R.array.androidColors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
if (frameLayout != null) {
frameLayout.setBackgroundColor(randomAndroidColor);
frameLayout.setTag(randomAndroidColor);
}
Pass the tag value to the activity:
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ReadActivity.class);
long poemId = (Long) v.getTag();
intent.putExtra("randomAndroidColor", (int) frameLayout.getTag());
onPoemClickListener.onPoemClick(poemId);
// presumably you trimmed out something that actually starts the Intent
}
And retrieve the color:
// randomAndroidColor should be an int now
randomAndroidColor = intent.getIntExtra("randomAndroidColor", 0);
toolbar.setBackgroundColor(randomAndroidColor);
i think problem is frameLayout.getBackground() not returning a color int, it return a drawable and so when you use toString() on that drawable, it won't return a color string but something else instead.
You can use Ben P's coding way to solve this problem, it's nice.

ArrayList is clearing when new values are inserting in adaper

I have a recycler view which is showing fruit list. Each item has a buy button.When I click the buy button of an item in the list, the details of that item should pass to the order list page through intent and should be displayed in recycler view.I have used ArrayList for passing the data.Then when I click the continue button it will come back to fruit list page and I want to buy another fruit.But my issue is, when I click the buy button of another item, only that particular item is displayed in the order list.the previous item is missing and the recycler view is showing only one row.(ie, latest data).Can any one please help?
this is the adapter code:
public ViewHolder(View view) {
super(view);
fruitname = (TextView) view.findViewById(R.id.category_name);
rate = (TextView) view.finenter code heredViewById(R.id.rate);
buy = (TextView) view.findViewById(R.id.buy);
mProfilepic = (ImageView) view.findViewById(R.id.profilepic);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View rootView = LayoutInflater.
from(mContext).inflate(R.layout.list_item, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
rootView.setLayoutParams(lp);
return new ViewHolder(rootView);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
item = mListItem.get(position);
final ViewHolder mViewHolder = (ViewHolder) viewHolder;
mViewHolder.fruitname.setText(item.get_name());
mViewHolder.rate.setText(item.get_email()+"/kg");
}
mViewHolder.buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
item1.set_contact(mListItem.get(position).get_designation());
item1.set_bank_fee(mListItem.get(position).get_name());
item1.set_category(mListItem.get(position).get_email());
dataItem.add(item1);
Intent intent = new Intent(mContext,OrderListActivity.class);
intent.putExtra("arraylist",dataItem);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mListItem.size();
}
note:I have used notifyDataSetChanged.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order_list);
mrecyclerview = (RecyclerView)findViewById(R.id.fruits_recycler);
mrecyclerview.setLayoutManager(new
LinearLayoutManager(getApplicationContext()));
dataItem =
(ArrayList<ListItem>)getIntent().getSerializableExtra("arraylist");
mOrderAdapter = new OrderAdapter(OrderListActivity.this,dataItem);
mrecyclerview.setAdapter(mOrderAdapter);
mOrderAdapter.notifyDataSetChanged();
}
}
Try this .
Intent intent = new Intent(mContext,OrderListActivity.class);
// edited here
intent.putParcelableArrayListExtra("arraylist", productList);
mContext.startActivity(intent);
And next Activity .
ArrayList<ListItem>) dataItem = getIntent().getParcelableArrayListExtra("arraylist");
if (dataItem != null && dataItem.size() > 0) {
mOrderAdapter = new OrderAdapter(OrderListActivity.this, dataItem);
mrecyclerview.setAdapter(mOrderAdapter);
// remove this
// mOrderAdapter.notifyDataSetChanged();
}

Recycle View scrolls slow . How to fix it?

I just implemented expandable layout in recycle view .ExpandableLayout library
Issue : Recycle view scroll slow at first time . expand/collpase working good but list scroll slow
NOTE : Its working smoothly on 4 GB RAM Device but laggy scroll on 2 GB RAM Device . I tested with Moto g3 (2 GB RAM) and Moto
g5 Plus (4 GB RAM)
Data coming from web-service and passing array-list through adapter.
Layout row file (XML) in Nested Linear Layouts. (may be its viewgroups load but i also tried with Constraint layout .Still recycleview load laggy)
I am replacing view during expansion and collapse item view (I already commented that code. but still my recycle view is slow )
There is no use of any image storing in itemview .
Already tried setHasFixedSize , notifyDataChanged , setCache , adapter.setHasStableIds(true);
but still recycleview loads laggy at first time only .
Help me to fix this issue. I am still finding the issue !
You can check my Adapter Code!
public class PendingOrdersAdapter extends RecyclerView.Adapter<PendingOrdersAdapter.ViewHolder> {
public LayoutInflater mInflater;
public HashSet<Integer> mExpandedPositionSet = new HashSet<>();
Context context;
ArrayList<CustomerDetails> list;
CustomerDetails details;
public PendingOrdersAdapter(Context context, ArrayList<CustomerDetails> list) {
this.context = context;
this.list = list;
this.mInflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = mInflater.inflate(R.layout.pending_order_item, parent, false);
return new ViewHolder(item);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
details = list.get(position);
holder.updateItem(position, holder);
holder.tvOrderNo.setText("" + details.getOrderID());
holder.tvCustomerName.setText("" + details.getCustomerName());
holder.tvTotalPrice.setText("" + details.getTotalPrice());
holder.tvCustomerContactNo.setText("" + details.getPrimaryContactNo());
holder.tvProductWeight.setText("" + details.getProductWeight());
holder.tvCustomerStatus.setText("" + details.getCustomerStatus());
holder.tvDeliveryManStatus.setText("" + details.getDeliveryManStatus());
holder.tvAddress.setText("" + details.getAddress());
holder.tvDeliveryMan.setText("" + details.getCustomerName() + " ( " + details.getPrimaryContactNo() + " ) ");
holder.tvTime.setText("" + details.getTime());
holder.tvPickUpDate.setText("" + details.getPickupDate());
holder.tvDeliveryCharge.setText("" + details.getDeliveryCharge());
//Opening DialogFragment on Click Listner
holder.tvDeliveryMan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) (context);
android.app.FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
android.app.Fragment prev = activity.getFragmentManager().findFragmentByTag("dvdialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DeliveryManDetailsDialog newFragment = new DeliveryManDetailsDialog();
newFragment.show(ft, "dvdialog");
}
});
holder.tvAddress.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2;
//Address icon click listner right side
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (holder.tvAddress.getRight() - holder.tvAddress.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
Intent intent = new Intent(context, RouteActivity.class);
intent.putExtra("custLat", details.getCustLatitude());
intent.putExtra("custLong", details.getCustLongitude());
intent.putExtra("boLat", details.getBoLatitude());
intent.putExtra("boLong", details.getBosLongitude());
context.startActivity(intent);
}
return true;
}
return true;
}
});
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return list.size();
}
public void registerExpand(int position, ViewHolder holder) {
if (mExpandedPositionSet.contains(position)) {
//Replacing views at runtime and arrow animation
ViewGroupUtils.replaceView(holder.timeLayout, holder.statusLayout);
holder.orderbox.setBackgroundResource(R.drawable.box_fill_drawable);
holder.ivArrow.animate().rotation(360).start();
removeExpand(position);
} else {
ViewGroupUtils.replaceView(holder.statusLayout, holder.timeLayout);
holder.orderbox.setBackgroundResource(R.drawable.box_fill_drawable_top);
holder.ivArrow.animate().rotation(180).start();
addExpand(position);
}
}
public void removeExpand(int position) {
mExpandedPositionSet.remove(position);
}
public void addExpand(int position) {
mExpandedPositionSet.add(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ExpandableLayout expandableLayout;
public LinearLayout orderbox, orderbox_bottom;
public ImageView ivArrow;
public TextView tvAddress, tvOrderNo, tvCustomerName, tvTotalPrice, tvCustomerContactNo;
public TextView tvProductWeight, tvCustomerStatus, tvDeliveryManStatus;
public TextView tvDeliveryCharge, tvDeliveryMan, tvTime;
public TextView tvPickUpDate;
public LinearLayout statusLayout, statusParentLayout, timeLayout, timeParentLayout, addressLayout;
public ViewHolder(final View itemView) {
super(itemView);
expandableLayout = (ExpandableLayout)
itemView.findViewById(R.id.expandable_layout);
orderbox = (LinearLayout) itemView.findViewById(R.id.orderbox);
orderbox_bottom = (LinearLayout)
itemView.findViewById(R.id.orderbox_bottom);
ivArrow = (ImageView) itemView.findViewById(R.id.ivArrow);
tvOrderNo = (TextView) itemView.findViewById(R.id.tvOrderNo);
tvCustomerName = (TextView)
itemView.findViewById(R.id.tvCustomerName);
tvTotalPrice = (TextView)
itemView.findViewById(R.id.tvTotalPrice);
tvCustomerContactNo = (TextView)
itemView.findViewById(R.id.tvCustomerContactNo);
tvProductWeight = (TextView)
itemView.findViewById(R.id.tvProductWeight);
tvCustomerStatus = (TextView)
itemView.findViewById(R.id.tvCustomerStatus);
tvDeliveryManStatus = (TextView)
itemView.findViewById(R.id.tvDeliveryManStatus);
tvDeliveryCharge = (TextView)
itemView.findViewById(R.id.tvDeliveryCharge);
tvAddress = (TextView) itemView.findViewById(R.id.tvAddress);
tvDeliveryMan = (TextView)
itemView.findViewById(R.id.tvDeliveryMan);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPickUpDate = (TextView)
itemView.findViewById(R.id.tvPickUpDate);
statusParentLayout = (LinearLayout)
itemView.findViewById(R.id.statusParentLayout);
statusLayout = (LinearLayout)
itemView.findViewById(R.id.statusLayout);
timeParentLayout = (LinearLayout)
itemView.findViewById(R.id.timeParentLayout);
timeLayout = (LinearLayout)
itemView.findViewById(R.id.timeDateLayout);
addressLayout = (LinearLayout)
itemView.findViewById(R.id.addressLayout);
}
public void updateItem(final int position, final ViewHolder holder) {
holder.orderbox.setBackgroundResource(R.drawable.box_fill_drawable_top);
holder.expandableLayout.setOnExpandListener(new ExpandableLayout.OnExpandListener() {
#Override
public void onExpand(boolean expanded) {
registerExpand(position, holder);
}
});
expandableLayout.setExpand(mExpandedPositionSet.contains(position));
}
}
Calling Adapter from Fragment
** PendingOrdersAdapter adapter = new PendingOrdersAdapter(getActivity(), detailsArrayList);
recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();**
Make one class, for example, Util and added this method to the class and use it.
public static void setDivider(Context context, RecyclerView recyclerView, RecyclerView.LayoutManager layoutManager) {
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
DividerItemDecoration horizontalDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
Drawable horizontalDivider = ContextCompat.getDrawable(context, R.drawable.horizontal_divider);
horizontalDecoration.setDrawable(horizontalDivider);
recyclerView.addItemDecoration(horizontalDecoration);
}
here first parameter is context, second one pass your recyclerview and third one pass the layout manager.
if you have more stuff then change the CacheSize
use this
recyclerView.setNestedScrollingEnabled(false);

Android: Select ListView Items and get the Objects

i made a custom listView having two textViews..for example student name and roll no...
now i want to implement a selection...for example..i will click on few students in the listview and the object should get saved somewhere ...for example:
ClassList.add(new StudentList(99,"student1","code"));
ClassList.add(new StudentList(70,"student2","code"));
ClassList.add(new StudentList(20,"student3","code"));
ClassList.add(new StudentList(30,"student4","code"));
adapter = new StudentListViewAdapter(this, ClassList,"code");
listView.setAdapter(adapter);
now i should be able to set another method for example:
ClassList2=listView.getSelectedStudents();
this should return the selected students..for example if i select student 1,student 2 it should return Student List Objects for both of them so i can access there roll and Code too
And there is another problem...when i deselect it should remove that object from the list..
It would be really helpfull if someone will write a sample code
This is how i do it..but i don't think it is really a good method
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (ItemView == null) {
ItemView = inflater.inflate(R.layout.customvistview_atd, parent, false);
}
//find the hotels to work with
final studentlist currentList = totalClass_list.get(position);
//fill the view
final TextView textview_studentName = (TextView) ItemView.findViewById(R.id.textview_atd_studentName);
textview_studentName.setText((currentList.getName()));
final TextView textview_studentRollno = (TextView) ItemView.findViewById(R.id.textview_atd_studentRollno);
textview_studentRollno.setText((currentList.getRoll_no() + ""));
final CardView cardView = (CardView) ItemView.findViewById(R.id.card_view_atd);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i = 0; i < presentStudents.size(); i++) {
if (presentStudents.get(i).getMindex() == position) {
System.out.println("m-index : "+presentStudents.get(i).getMindex());
System.out.println("position : "+position);
isChecked = true;
System.out.println("I am in the loop, I am at position: "+i);
me = i;
break;
}
}
if (isChecked) {
presentStudents.remove(me);
isChecked = false;
ColorDrawable[] color = {new ColorDrawable(Color.parseColor("#198b9f")), new ColorDrawable(Color.WHITE)};
TransitionDrawable trans = new TransitionDrawable(color);
cardView.setBackground(trans);
trans.startTransition(1500);
textview_studentName.setTextColor(Color.GRAY);
textview_studentName.setTextColor(Color.GRAY);
//cardView.setBackgroundColor(Color.WHITE);
System.out.println("I am in isChecked");
} else {
presentStudents.add(new tempclass(currentList.getRoll_no(),atdCode,position));
ColorDrawable[] colorCard = {new ColorDrawable(Color.WHITE), new ColorDrawable(Color.parseColor("#198b9f"))};
TransitionDrawable trans = new TransitionDrawable(colorCard);
cardView.setBackground(trans);
trans.startTransition(1500);
textview_studentName.setTextColor(Color.WHITE);
textview_studentName.setTextColor(Color.WHITE);
// cardView.setBackgroundColor(Color.BLUE);
System.out.println("I am in else, making it blue");
}
}
});
you can use this one
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
StudentLists studentList = listView.getItemAtPosition(i);//selected object
adapter.dismiss(); // If you want to close the adapter
}
});

Categories

Resources