Here is code.
public class QuotesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int PRICE_PICKER_MAX_VALUE = 1000000;
private static final int PRICE_PICKER_MIN_VALUE = 500;
private static final int PRICE_PICKER_INTERVAL_VALUE = 500;
private List<Quote> mQuotes;
private String[] mPickerValues;
private String mSelectedQuotePrice;
private OnQuoteActionListener mListener;
private Context mContext;
/**
* #param context a context
* #param quotes the data for this adapter
*/
public QuotesAdapter(Context context, List<Quote> quotes) {
mContext = context;
mQuotes = quotes;
}
private String[] getArrayWithSteps (int iMaxValue, int iMinValue, int iStep) {
int iStepsArray = (iMaxValue-iMinValue)/iStep+1; //get the lenght array that will return
String[] arrayValues= new String[iStepsArray]; //Create array with length of iStepsArray
for(int i = 0; i < iStepsArray; i++) {
arrayValues[i] = String.valueOf(iMinValue + (i*iStep));
}
return arrayValues;
}
private void setPricePickerSelection (String valueToSet, Spinner numPicker) {
for (int i = 0; i < mPickerValues.length; i++)
if (mPickerValues[i].equals(valueToSet)) {
numPicker.setSelection(i, true);
}
}
#Override
public int getItemCount() {
return mQuotes.size();
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int rawPosition) {
final ItemViewHolder itemViewHolder = (ItemViewHolder) viewHolder;
final Quote item = mQuotes.get(rawPosition);
//Update from / to city information
String fromCity = item.getFromCity();
String toCity = item.getToCity();
Typeface myFont=Typeface.createFromAsset(mContext.getAssets(), "fonts/Rajdhani-Bold.ttf");
if (StringUtils.isNotBlank(fromCity) && StringUtils.isNotBlank(toCity)) {
StringBuffer sb = new StringBuffer(" ").append(fromCity).append(" ");
itemViewHolder.mFromCityView.setText(sb.toString());
itemViewHolder.mToCityView.setText(" " + toCity);
myFont= Typeface.createFromAsset(mContext.getAssets(), "fonts/Rajdhani-SemiBold.ttf");
itemViewHolder.mFromCityView.setTypeface(myFont);
itemViewHolder.mToCityView.setTypeface(myFont);
myFont=Typeface.createFromAsset(mContext.getAssets(), "fonts/Rajdhani-Medium.ttf");
itemViewHolder.mToCityTitleView.setTypeface(myFont);
itemViewHolder.mFromCityTitleView.setTypeface(myFont);
ViewUtils.setMultipleToVisible(itemViewHolder.mFromCityView, itemViewHolder.mToCityView, itemViewHolder.mFromCityTitleView, itemViewHolder.mToCityTitleView);
} else {
ViewUtils.setMultipleToGone(itemViewHolder.mFromCityView, itemViewHolder.mToCityView, itemViewHolder.mFromCityTitleView, itemViewHolder.mToCityTitleView);
}
//Update the Logistics Company name
itemViewHolder.mCompanyView.setText(item.getLogisticsCompanyName());
myFont=Typeface.createFromAsset(mContext.getAssets(), "fonts/Rajdhani-Bold.ttf");
itemViewHolder.mCompanyView.setTypeface(myFont);
myFont=Typeface.createFromAsset(mContext.getAssets(), "fonts/Rajdhani-Medium.ttf");
itemViewHolder.mRequestDateView.setText(item.getRequestDate());
itemViewHolder.mCloesByView.setText(item.getRequestEndDate());
itemViewHolder.mTruckType.setText(item.getTruckType());
itemViewHolder.mCapacity.setText(item.getCapacity() + "");
itemViewHolder.mRequestDateView.setTypeface(myFont);
itemViewHolder.mCloesByView.setTypeface(myFont);
itemViewHolder.mTruckType.setTypeface(myFont);
itemViewHolder.mCapacity.setTypeface(myFont);
int price = item.getMoney();
//Load the picker values in defined intervals
mPickerValues = getArrayWithSteps(PRICE_PICKER_MAX_VALUE, PRICE_PICKER_MIN_VALUE, PRICE_PICKER_INTERVAL_VALUE);
// Creating adapter for truck options spinner
ArrayAdapter<String> quotePriceOptionsAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_dropdown_item, mPickerValues);
// attaching data adapter to spinner
itemViewHolder.mPricePicker.setAdapter(quotePriceOptionsAdapter);
setPricePickerSelection(String.valueOf(price), itemViewHolder.mPricePicker);
itemViewHolder.mPricePicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int selectedQuotePricePosition = parent.getSelectedItemPosition();
mSelectedQuotePrice = mPickerValues[selectedQuotePricePosition];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
itemViewHolder.mIgnoreQuoteView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onIgnore(item.getRequestID());
}
}
});
itemViewHolder.mQuoteButtonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
item.setMoney(Integer.parseInt(mSelectedQuotePrice));
mListener.onQuote(item);
}
}
});
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_quote_item,
parent, false);
return new ItemViewHolder(view);
}
public void setQuoteActionListener(OnQuoteActionListener listener) {
mListener = listener;
}
public interface OnQuoteActionListener {
public void onQuote(Quote quote);
public void onIgnore(int requestID);
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView mFromCityTitleView ;
public TextView mFromCityView;
public TextView mToCityView;
public TextView mToCityTitleView;
public TextView mCompanyView ;
public TextView mRequestDateView;
public TextView mCloesByView;
public TextView mTruckType;
public TextView mCapacity;
public Button mQuoteButtonView;
public Button mIgnoreQuoteView;
public Spinner mPricePicker;
public ItemViewHolder(View v) {
super(v);
mFromCityTitleView = (TextView) v.findViewById(R.id.quote_item_from);
mFromCityView = (TextView) v.findViewById(R.id.quote_item_fromcity);
mToCityTitleView = (TextView) v.findViewById(R.id.quote_item_to);
mToCityView = (TextView) v.findViewById(R.id.quote_item_tocity);
mCompanyView = (TextView) v.findViewById(R.id.quote_company);
mRequestDateView = (TextView) v.findViewById(R.id.quote_item_requestedDate);
mCloesByView = (TextView) v.findViewById(R.id.quote_item_closesby);
mTruckType = (TextView) v.findViewById(R.id.quote_item_truck_type);
mCapacity = (TextView) v.findViewById(R.id.quote_item_capacity);
mQuoteButtonView = (Button) v.findViewById(R.id.button_quote);
mIgnoreQuoteView = (Button) v.findViewById(R.id.button_ignore);
mPricePicker = (Spinner) v.findViewById(R.id.quote_pricePicker);
}
}
}`
Screenshot
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:background="#color/back_white"
android:orientation="horizontal">
<Spinner
android:id="#+id/quote_pricePicker"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="left"/>
</LinearLayout>
While Creating Adapter for your Spinner give custom layout instead of predefined one
Create xml named spinner_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cust_view"
android:layout_width="match_parent"
android:textColor="#color/black"
android:textSize="12sp"
android:layout_height="36dp"
android:gravity="left|center_vertical"/>
Here you can change the color Text size and width and height of the Elements in the spinner by modifying this textview
Use it like this while creating Adapter
ArrayAdapter<String> adapter=new ArrayAdapter<String>(context, R.layout.spinner_row,yourlist);
The Last task is routine
spinner.setAdapter(adapter);
I hope this will help you.
Related
I'm trying to change an ImageView in my RecyclerView. I need to change ImageView every time I click the RecyclerView. So, when I click it once it changes to a tick, then I click it again it changes again to be like the beginning, and when I click it again I want to bring up the tick like when I pressed it the first time.
public class RecyclerViewAdapter1 extends RecyclerView.Adapter<RecyclerViewAdapter1.ViewHolder> {
private LayoutInflater inflater;
private FragmentCommunication mCommunicator;
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<String> arrayList;
private ArrayList<Integer> IDList;
private ArrayList<Integer> polikhusus;
private int tekan = 0;
private GlobalClass globalVariable;
private static int lastClickedPosition = -1;// Variable to store the last clicked item position
RecyclerViewAdapter1(ArrayList<String> pintuMasuk, ArrayList<Integer> PoliID, ArrayList<Integer> poli, OnTextClickListener listener) {
this.arrayList = pintuMasuk;
this.IDList = PoliID;
this.polikhusus = poli;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_poli_design, parent, false);
ViewHolder VH = new ViewHolder(V);
return VH;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView PintuMasuk;
private ImageView Meme2;
private RelativeLayout ItemList3;
private int selectedIndex;
private Integer PoliID;
public ViewHolder(View itemView) {
super(itemView);
PintuMasuk = itemView.findViewById(R.id.poli);
Meme2 = itemView.findViewById(R.id.gbpoli);
ItemList3 = itemView.findViewById(R.id.item_list3);
}
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final String PintuMasuk = arrayList.get(position);
final Integer PoliID = IDList.get(position);
final Integer poli = polikhusus.get(position);
holder.PintuMasuk.setText(PintuMasuk);
holder.ItemList3.setTag(position);
holder.Meme2.setImageResource(R.drawable.pintumasuk);
holder.ItemList3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
globalVariable = (GlobalClass) view.getContext().getApplicationContext();
globalVariable.PoliID = PoliID;
if(position != lastClickedPosition){
holder.Meme2.setImageResource(R.drawable.policheck);
Snackbar.make(view, "Anda memilih : "+PoliID+" "+PintuMasuk, Snackbar.LENGTH_SHORT).show();
Log.i(LOG_TAG," Clicked on Item " + position);
}else {
// for cancel
Snackbar.make(view, "Anda membatalkan pilihan Anda", Snackbar.LENGTH_SHORT).show();
globalVariable.PoliID = 0;
}
if (lastClickedPosition != -1)
notifyItemChanged(lastClickedPosition);
lastClickedPosition = position;
}
});
}
#Override
public int getItemCount () {
return this.arrayList.size();
}
}
enter image description here
I have a recycler view to show an activity timeline and three floating buttons that click to add activity. How can I code three buttons to a different view? How can I pass the condition to the Adapter?
Now I can show only one viewType.
thx a lot.
Adapter.java
public class TripAdapter extends RecyclerView.Adapter<TripAdapter.TripHolder> {
private List<Trip> trips = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public TripHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_item, parent, false);
return new TripHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TripHolder holder, int position) {
Trip currentTrip = trips.get(position);
holder.textViewLodgingTitle.setText(currentTrip.getLodgingTitle());
holder.textTextViewLodgingCheckInDateTime.setText(currentTrip.getLodgingCheckInDateTime());
holder.textTextViewLodgingCheckOutDateTime.setText(currentTrip.getLodgingCheckOutDateTime());
holder.textViewLodgingAddress.setText(currentTrip.getLodgingAddress());
}
#Override
public int getItemCount() {
return trips.size();
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
notifyDataSetChanged();
}
public Trip getTripAt(int position) {
return trips.get(position);
}
class TripHolder extends RecyclerView.ViewHolder {
//lodging
private TextView textViewLodgingTitle;
private TextView textTextViewLodgingCheckInDateTime;
private TextView textTextViewLodgingCheckOutDateTime;
private TextView textViewLodgingAddress;
private TextView textViewLodgingPhone;
private TextView textViewLodgingWebsite;
private TextView textViewLodgingEmail;
public TripHolder(#NonNull View itemView) {
super(itemView);
context = itemView.getContext();
textViewLodgingTitle = itemView.findViewById(R.id.text_view_title);
textTextViewLodgingCheckInDateTime = itemView.findViewById(R.id.text_view_start_date_time);
textTextViewLodgingCheckOutDateTime = itemView.findViewById(R.id.text_view_end_date_time);
textViewLodgingAddress = itemView.findViewById(R.id.text_view_description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(trips.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Trip trip);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
MainActivity.java
//adapter
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TripAdapter adapter = new TripAdapter();
recyclerView.setAdapter(adapter );
tripViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(TripViewModel.class);
tripViewModel.getAllTrips().observe(this, new Observer<List<Trip>>() {
#Override
public void onChanged(#Nullable List<Trip> trips) {
adapter.setTrips(trips);
}
});
//this on onActivityResult()
else if (requestCode == ADD_LODGING && resultCode == Activity.RESULT_OK) {
//get data from lodging activity
String lodgingTitle = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_TITLE);
String lodgingCheckInDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_IN_DATE_TIME);
String lodgingCheckOutDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_OUT_DATE_TIME);
String lodgingDescription = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_DESCRIPTION);
String lodgingAddress = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_ADDRESS);
String lodgingPhone = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_PHONE);
String lodgingWebsite = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_WEBSITE);
String lodgingEmail = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_EMAIL);
String lodgingImagePath = "test";
Trip lodging = new Trip(lodgingTitle, lodgingCheckInDateTime, lodgingCheckOutDateTime,lodgingDescription, lodgingAddress, lodgingPhone, lodgingWebsite, lodgingEmail,lodgingImagePath);
tripViewModel.insert(lodging);
Toast.makeText(this, "lodging save", Toast.LENGTH_SHORT).show();
}
My application I adapt from codinginflow channel.
https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}
I am developing an android app, where I am trying to implement one feature for Image gallary. Now, initially, I want to show some image url with their title name. I am using hashmap for mapping title with their image.I have the model class with two String fields url and title. But The problem is I am very new in the development field and now sure how to show the title based on image click. Here is my model Class
public class ImageModel implements Parcelable {
String name, url;
public ImageModel() {
}
protected ImageModel(Parcel in) {
name = in.readString();
url = in.readString();
}
public static final Creator<ImageModel> CREATOR = new Creator<ImageModel>() {
#Override
public ImageModel createFromParcel(Parcel in) {
return new ImageModel(in);
}
#Override
public ImageModel[] newArray(int size) {
return new ImageModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
}
}
Now the Main activity where I create a Hashmap with image and title to show those into views.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
HashMap<String, String> h1 = new HashMap<>();
String[] imgUrls = {"https://images.unsplash.com/photo-1444090542259-0af8fa96557e?q=80&fm=jpg&w=1080&fit=max&s=4b703b77b42e067f949d14581f35019b",
"https://images.unsplash.com/photo-1439546743462-802cabef8e97?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1441155472722-d17942a2b76a?q=80&fm=jpg&w=1080&fit=max&s=80cb5dbcf01265bb81c5e8380e4f5cc1"};
String[] imgNames = {"name1","name2","name3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
}));
}
}
GalleryAdapterCode
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<ImageModel> data = new ArrayList<>();
public GalleryAdapter(Context context, List<ImageModel> data) {
this.context = context;
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
((MyItemHolder) holder).mTextView.setText(data.get(position).getName());
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
My XML Class for item list row is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="#+id/item_img"
android:layout_width="match_parent"
android:layout_height="188dp"
android:adjustViewBounds="true"
android:background="#color/colorAccent"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7000"
android:orientation="vertical"
android:padding="10dp"
android:layout_alignBottom="#+id/item_img"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textView"
android:text="Headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="15dp"
android:textStyle="normal|bold"
/>
</LinearLayout>
</RelativeLayout>
Create two String arrays one containing image urls and other names in MainActivity.
String[] imgUrls = {"url1","url2","url3"};
String[] imgNames = {"name1","name2","name3"};
Iterate over those arrays and create a list of the model class.
ArrayList<ImageModel> data = new ArrayList<ImageModel>();
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
Add a TextView in your RecyclerView row layout R.layout.list_item.
In your adapter use this TextView to set name of image.
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.item_textview);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
holder.mTextView.setText(data.get(position).getName());
}
Rest of your code will be the same.
I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}