Android : Binding to update UI - android

In my android application, I have below classes. I want to bind these classes in UI to display the UI content based on object data.
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="java.util.Map"/>
<import type="java.util.List"/>
<variable name="itemContainerInformation" type="com.myApp.Models.ItemsContainerInformation"/>
</data>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/cardview_light_background"
tools:context="com.myApp.Fragments.DetailedViewFragment"
android:id="#+id/layout_detailed_view">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemInformation.t1Caption}"
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_t1_header"
android:layout_below="#+id/textView_date_header"
android:textStyle="normal|bold"
android:textSize="20sp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:textColor="#color/cardview_light_background"
android:background="#color/colorPrimary"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.currentDateHeaderCaption}"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:textAlignment="center"
android:textColor="#color/colorAccent"
android:background="#color/colorPrimaryDark"
android:id="#+id/textView_date_header"
android:textStyle="normal|bold"
android:layout_marginTop="10dp"
android:textSize="24sp" />
<LinearLayout android:orientation="horizontal"
android:id="#+id/linear_layout_information"
android:layout_below="#+id/textView_day_t1_header"
android:background="#color/fall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout android:orientation="vertical"
android:id="#+id/linear_layout_day_information_list"
android:layout_weight="1" android:layout_height="fill_parent" android:layout_width="0dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[0].Caption}"
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_information1"
android:textStyle="normal|bold"
android:textSize="16sp"
android:layout_marginTop="30dp"
android:textColor="#color/colorPrimary" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[1].Caption}"
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_information2"
android:textStyle="normal|bold"
android:textSize="16sp"
android:textColor="#color/colorPrimary" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[2].Caption}"
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_information3"
android:textStyle="normal|bold"
android:textSize="16sp"
android:textColor="#color/colorPrimary" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[3].Caption}"
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_information4"
android:textStyle="normal|bold"
android:textSize="16sp"
android:textColor="#color/colorPrimary" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[4].Caption}"
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_information5"
android:textStyle="normal|bold"
android:textSize="16sp"
android:textColor="#color/colorPrimary" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" "
android:textAlignment="textStart"
android:gravity="start"
android:id="#+id/textView_day_information6"
android:textStyle="normal|bold"
android:layout_marginBottom="20dp"
android:textSize="16sp"
android:textColor="#color/colorPrimary" />
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:id="#+id/linear_layout_day"
android:layout_weight="1" android:layout_height="match_parent" android:layout_width="0dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/linear_layout_day_information_list"
android:text="#{itemContainerInformation.currentDate}"
android:textAlignment="viewEnd"
android:gravity="end"
android:id="#+id/textView_day"
android:textStyle="normal|bold"
android:textSize="100dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:textColor="#color/colorPrimary" />
</LinearLayout>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:id="#+id/linear_layout_information_bottom"
android:layout_below="#+id/linear_layout_information"
android:background="#color/fall"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[5].Caption}"
android:textAlignment="viewEnd"
android:gravity="end"
android:id="#+id/textView_day_information_bottom1"
android:textStyle="normal|bold"
android:textSize="16sp"
android:layout_marginTop="0dp"
android:textColor="#color/colorPrimary" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{itemContainerInformation.itemInformations[6].Caption}"
android:textAlignment="viewEnd"
android:gravity="end"
android:id="#+id/textView_day_information_bottom2"
android:layout_below="#+id/textView_day_information_bottom1"
android:textStyle="normal|bold"
android:textSize="16sp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:textColor="#color/colorPrimary" />
</LinearLayout>
ItemInformation.java
public class ItemInformation extends BaseObservable {
private String caption;
private int lineIndex;
private int lineFontSize;
private int lineFontColor;
private int lineIndentation;
private int imageIndex;
public ItemInformation()
{
}
#Bindable
public String getCaption() { return caption; }
public void setCaption(String caption) {
this.caption = caption;
notifyPropertyChanged(BR.caption);
}
#Bindable
public int getLineIndex() { return lineIndex; }
public void setLineIndex(int lineIndex) {
this.lineIndex = lineIndex;
notifyPropertyChanged(BR.lineIndex);
}
#Bindable
public int getLineFontSize() { return lineFontSize; }
public void setLineFontSize(int lineFontSize) {
this.lineFontSize = lineFontSize;
notifyPropertyChanged(BR.lineFontSize);
}
#Bindable
public int getLineFontColor() { return lineFontColor; }
public void setLineFontColor(int lineFontColor) {
this.lineFontColor = lineFontColor;
notifyPropertyChanged(BR.lineFontColor);
}
#Bindable
public int getLineIndentation() { return lineIndentation; }
public void setLineIndentation(int lineIndentation) {
this.lineIndentation = lineIndentation;
notifyPropertyChanged(BR.lineIndentation);
}
#Bindable
public int getImageIndex() { return imageIndex; }
public void setImageIndex(int imageIndex) {
this.imageIndex = imageIndex;
notifyPropertyChanged(BR.imageIndex);}
public static int GetColorInformation(String fontcolor)
{
return Color.parseColor(fontcolor);
//int desiredColour = getResources().getColor(getResources().getIdentifier("my_color", "color"
}
}
ItemContainerInformation.java
public class ItemContainerInformation extends BaseObservable {
private List<ItemInformation> itemInformations = new ArrayList<ItemInformation>();
private String currentDate;
private String currentDateHeaderCaption;
private String t1Caption;
private int rowIndex;
private int columnIndex;
private int currentMonth;
private int currentYear;
public ItemContainerInformation()
{
Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
}
public ItemContainerInformation(String currentDate) {
this.currentDate = currentDate;
}
#Bindable
public String getCurrentDate() {
return currentDate;
}
public void setCurrentDate(String currentDate) {
this.currentDate = currentDate;
notifyPropertyChanged(BR.currentDate);
}
#Bindable
public String getCurrentDateHeaderCaption() {
return currentDateHeaderCaption;
}
public void setCurrentDateHeaderCaption(String currentDateHeaderCaption) {
this.currentDateHeaderCaption = currentDateHeaderCaption;
notifyPropertyChanged(BR.currentDateHeaderCaption);
}
#Bindable
public String getT1Caption() {
return t1Caption;
}
public void setT1Caption(String t1Caption) {
this.t1Caption = t1Caption;
notifyPropertyChanged(BR.t1Caption);
}
#Bindable
public int getRowIndex() {
return rowIndex;
}
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
notifyPropertyChanged(BR.rowIndex);
}
#Bindable
public int getColumnIndex() {
return columnIndex;
}
public void setColumnIndex(int columnIndex) {
this.columnIndex = columnIndex;
notifyPropertyChanged(BR.columnIndex);
}
#Bindable
public int getCurrentMonth() {
return currentMonth;
}
public void setCurrentMonth(int currentMonth) {
this.currentMonth = currentMonth;
notifyPropertyChanged(BR.currentMonth);
}
#Bindable
public int getCurrentYear() {
return currentYear;
}
public void setCurrentYear(int currentYear) {
this.currentYear = currentYear;
notifyPropertyChanged(BR.currentYear);
}
#Bindable
public List<ItemInformation> getItemInformations() {
return itemInformations;
}
public void setItemInformations(List<ItemInformation> itemInformations) {
this.itemInformations = itemInformations;
notifyPropertyChanged(BR.itemInformations);
}
}
DetailedViewFagment
public class DetailedViewFragment extends Fragment {
ItemContainerInformation currentInormationItem;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_detailed_view, container, false);
if(currentInormationItem == null)
{
currentInormationItem = new ItemContainerInformation("100");
List<ItemInformation> dailyItems = new ArrayList<ItemInformation>();
for(int i = 0; i < 10; i++)
{
ItemInformation item = new ItemInformation();
item.setCaption("Caption_");
dailyItems.add(item);
}
currentDayInormationItem.setItemInformations(dailyItems);
}
FragmentDetailedDayViewBinding binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_detailed_view, container, false);
View view = binding.getRoot();
//here data must be an instance of the class MarsDataProvider
binding.setDateInformation(currentDayInormationItem);
return v;
}
// This method is used to update the object from 'ParentItem'
// So when a UI click happens in the ParentFragment this method is called from ParentFragment
// which updates the objects. Now this updated object () will have new values which i want to update in the UI inside detailed view fragment.
public void UpdateDetailedDayView(DateInformation dayInormationItem)
{
// Should update all textviews in the child view but not working???
currentDayInormationItem = dayInormationItem;
}
}
ParentViewFragment
public class ParentViewFragment extends Fragment {
// This is inside the parent fragment class which has multiple items populated using Adapter and ViewHolder
// On item click of the UI i want to update the 'DetailedViewFragment'.
MyRecyclerViewAdapter.OnItemClickListener onItemClickListener = new MyRecyclerViewAdapter.OnItemClickListener() {
#Override
public void onItemClick(ItemInformation itemInformation) {
Toast.makeText(getContext(), "Item Clicked --- " + itemInformation.getCurrentDate(), Toast.LENGTH_LONG).show();
// On click i am creating new fragment and updating it
DetailedViewFragment detailedView = new DetailedViewFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.month_detailed_view_container, detailedView).commit();
detailedView.UpdateDetailedDayView(itemInformation);
}
};
}
Basically i have different textviews in UI and respective UI properties are stored in object like indentation, foreground color, font size etc. How I can bind this information to a textview?
I am not able to view the text using this line, can someone help me to correct my mistake in the below line and display the text using the specific identation and forground color.
android:text="#{itemContainerInformation.itemInformations[0].Caption}"
How I can bind the object and update the UI based on object data?
Thanks.

Related

Modify textview of parent layout from adapter xamarin android

Sorry, I'm using google translate.
Hello, I am developing an application in xamarin android with visual studio 2017 to take requests where I send information from a fragment to a List<EN_WishDetail> to store the selection of items and this is dumped to an adapter to display it in another fragment.
my problem is that the parent layout loads a custom listview where I have 2 buttons to increase and decrease the quantities of the items this works correctly, likewise in the parent layout it has two textviews to count the number of items and the total value of the order , I want that when increasing the amount this also updates the textview of the parent layout from the adapter where the button functions are.
How can I access the parent layout from the adapter and modify its value.
layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_weight="5">
<TextView
android:text="Cesta de Pedido"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:gravity="center"
android:textSize="20dip"
android:textColor="#color/primaryDark" />
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/List" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_weight="1"
android:background="#000000">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/itemItems"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="6dp"
android:text="(0) Items"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="left"
android:layout_weight="3"
android:textColor="#FFFFFF"/>
<Button
android:id="#+id/btnClear"
android:layout_width="50dp"
android:layout_height="40dp"
android:text="Clear"
android:textAppearance="?android:attr/textAppearanceSmall"
android:background="#drawable/Blue_button"
style="#style/button_text"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/itemTotal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="6dp"
android:text="S/. 0.00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="left"
android:layout_weight="3"
android:textColor="#FFFFFF"/>
<Button
android:id="#+id/btnSave"
android:layout_width="50dp"
android:layout_height="40dp"
android:text="Guardar"
android:textAppearance="?android:attr/textAppearanceSmall"
android:background="#drawable/Blue_button"
style="#style/button_text"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
listview personalized
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/Image"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp"
android:src="#drawable/Pedidos"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/Articulo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#id/Image"
android:layout_toRightOf="#id/Image"
android:layout_marginTop="0dip"
android:text="This is Line1"
android:lines="2"
android:maxLines="2"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/colorTexto"/>
<TextView
android:id="#+id/MonedaU"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_below="#id/Articulo"
android:layout_marginTop="0dip"
android:text="S/."
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_toRightOf="#id/Image"/>
<TextView
android:id="#+id/PrecioU"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Articulo"
android:layout_marginTop="0dip"
android:text="This is line2"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_toRightOf="#id/MonedaU"
android:singleLine="true"/>
<TextView
android:id="#+id/MonedaT"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_below="#id/Articulo"
android:layout_marginTop="20dip"
android:text="S/."
android:textAppearance="?android:attr/textAppearanceListItem"
android:layout_toRightOf="#id/Image"
android:textStyle="bold"
android:textColor="#color/colorResaltado"/>
<TextView
android:id="#+id/Importe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Articulo"
android:layout_marginTop="20dip"
android:text="This is line3"
android:textAppearance="?android:attr/textAppearanceListItem"
android:layout_toRightOf="#id/MonedaT"
android:textStyle="bold"
android:textColor="#color/colorResaltado"/>
<Button
android:id="#+id/btnMin"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#id/Articulo"
android:layout_toLeftOf="#+id/Cantidad"
android:text="-"
android:textAppearance="?android:attr/textAppearanceSmall"
android:background="#drawable/red_button"
style="#style/button_text" />
<EditText
android:id="#+id/Cantidad"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/btnMax"
android:layout_marginTop="5dip"
android:layout_below="#id/Articulo"
android:textColor="#000000"
android:background="#FFFFFF"
android:text="0"
android:singleLine="true"
android:maxLines="1"
android:inputType="number"
android:gravity="center"
android:textAlignment="center"/>
<Button
android:id="#+id/btnMax"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#id/Articulo"
android:layout_toLeftOf="#+id/btnDel"
android:text="+"
android:textAppearance="?android:attr/textAppearanceSmall"
android:background="#drawable/red_button"
android:layout_gravity="right"
style="#style/button_text" />
<ImageButton
android:id="#+id/btnDel"
android:src="#drawable/Trash_"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#id/Articulo"
android:layout_alignParentRight="true"
style="#style/button_text" />
</RelativeLayout>
Fragment
public class WishFragment : Fragment
{
public WishFragment MyFragment()
{
return this;
}
public WishFragment()
{
RetainInstance = true;
}
private ListView WishlistView;
WishAdapter adapter;
List<EN_WishDetalle> List_Wish = new List<EN_WishDetalle>();
public override View OnCreateView(LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
//HasOptionsMenu = true;
var view = inflater.Inflate(Resource.Layout.Main_Wish, null);
WishlistView = view.FindViewById<ListView>(Resource.Id.List);
EditText txtCantidad = view.FindViewById<EditText>(Resource.Id.Cantidad);
List_Wish = Variables.WishDetalle;
adapter = new WishAdapter(Activity, List_Wish);
WishlistView.Adapter = adapter;
WishlistView = view.FindViewById<ListView>(Resource.Id.List);
Button buttonMax = view.FindViewById<Button>(Resource.Id.btnMax);
Button buttonMin = view.FindViewById<Button>(Resource.Id.btnMin);
ImageButton buttonDel = view.FindViewById<ImageButton>(Resource.Id.btnDel);
TextView txtContador = view.FindViewById<TextView>(Resource.Id.itemItems);
TextView txtTotal = view.FindViewById<TextView>(Resource.Id.itemTotal);
WishlistView.ItemClick += buttonMax_ItemClick;
txtContador.Text ="( " + List_Wish.Count.ToString() + " ) Items";
decimal suma = List_Wish.Sum(item => Convert.ToDecimal(item.importetotal));
txtTotal.Text = "S/. " + suma.ToString("N");
//WishlistView.ItemClick += buttonMin_ItemClick;
//WishlistView.ItemClick += buttonDel_ItemClick;
return view;
}
void buttonMax_ItemClick(object sender,AdapterView.ItemClickEventArgs e)
{
}
void buttonMin_ItemClick(object sender, AdapterView.ItemClickEventArgs x)
{
}
void buttonDel_ItemClick(object sender, AdapterView.ItemClickEventArgs z)
{
}
}
adapter
public class WishAdapter : BaseAdapter<EN_WishDetalle>
{
List<EN_WishDetalle> sList;
Context sContext;
public WishAdapter(Context context, List<EN_WishDetalle> list)
{
sList = list;
sContext = context;
}
public override EN_WishDetalle this[int position]
{
get
{
return sList[position];
}
}
public override int Count
{
get
{
return sList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = sList[position];
View view = convertView; // re-use an existing view, if one is available
MyViewHolder holder;
if (view != null)
{
holder = view.Tag as MyViewHolder;
holder.buttonDel.Tag = position;
//holder.buttonMax.Tag = position;
//holder.buttonMin.Tag = position;
}
else
{ // otherwise create a new one
holder = new MyViewHolder();
LayoutInflater inflater =
(LayoutInflater)sContext.GetSystemService(Context.LayoutInflaterService);
view = inflater.Inflate(Resource.Layout.item_Wish, null);
holder.txtPrecioU = view.FindViewById<TextView>(Resource.Id.PrecioU);
holder.txtArticulo = view.FindViewById<TextView>(Resource.Id.Articulo);
holder.txtCantidad = view.FindViewById<TextView>(Resource.Id.Cantidad);
holder.txtImporte = view.FindViewById<TextView>(Resource.Id.Importe);
holder.txtMonedaU = view.FindViewById<TextView>(Resource.Id.MonedaU);
holder.txtMonedaT = view.FindViewById<TextView>(Resource.Id.MonedaT);
holder.Art = view.FindViewById<ImageView>(Resource.Id.Image);
holder.buttonMax = view.FindViewById<Button>(Resource.Id.btnMax);
holder.buttonMin = view.FindViewById<Button>(Resource.Id.btnMin);
holder.buttonDel = view.FindViewById<ImageButton>(Resource.Id.btnDel);
holder.buttonMax.Click += delegate
{
sList[position].cantidad = sList[position].cantidad + 1;
sList[position].importetotal = Convert.ToString( sList[position].cantidad * Convert.ToDecimal(item.punitario));
holder.txtCantidad.SetText(Convert.ToString(sList[position].cantidad), TextView.BufferType.Normal);
string format_importe = (sList[position].cantidad * Convert.ToDecimal(item.punitario)).ToString("N");
holder.txtImporte.SetText(format_importe, TextView.BufferType.Normal);
};
holder.buttonMin.Click += delegate
{
if (sList[position].cantidad > 1) {
sList[position].cantidad = sList[position].cantidad - 1;
sList[position].importetotal = Convert.ToString(sList[position].cantidad * Convert.ToDecimal(item.punitario));
holder.txtCantidad.SetText(Convert.ToString(sList[position].cantidad), TextView.BufferType.Normal);
string format_importe = (sList[position].cantidad * Convert.ToDecimal(item.punitario)).ToString("N");
holder.txtImporte.SetText(format_importe, TextView.BufferType.Normal);
}
};
holder.buttonDel.Click += delegate
{ // we get the tag here for buttonDel
int x = (int)holder.buttonDel.Tag;
Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(sContext);
AlertDialog alert = dialog.Create();
alert.SetTitle("GumisaAPP");
alert.SetMessage("Eliminar item : (" + x.ToString() + ") - " + sList[position].codigo + sList[position].articulo);
alert.SetIcon(Resource.Drawable.Alerta);
alert.SetButton("OK", (c, ev) =>
{
sList.RemoveAt(position);
NotifyDataSetChanged();
});
alert.SetButton2("CANCEL", (c, ev) =>
{
});
alert.Show();
};
holder.buttonDel.Tag = position;
view.Tag = holder;
}
holder.txtPrecioU.Text = Convert.ToDecimal(item.punitario).ToString("N");
holder.txtArticulo.Text = item.articulo;
holder.txtCantidad.Text = item.cantidad.ToString();
holder.txtImporte.Text = Convert.ToDecimal(item.importetotal).ToString("N");
holder.txtMonedaU.Text = item.moneda;
holder.txtMonedaT.Text = item.moneda;
holder.Art.SetImageResource(Android.Resource.Color.Transparent);
if (sList[position].imagenproducto == "")
{
holder.Art.SetImageResource(Resource.Drawable.NoDisponible);
}
else
{
Android.Net.Uri myUri = (Android.Net.Uri.Parse(sList[position].imagenproducto));
//Art.SetImageURI(myUri);
holder.Art.SetImageURI(myUri);
}
return view;
}
public class MyViewHolder : Java.Lang.Object
{
public TextView txtPrecioU { get; set; }
public TextView txtArticulo { get; set; }
public TextView txtCantidad { get; set; }
public TextView txtImporte { get; set; }
public TextView txtMonedaU { get; set; }
public TextView txtMonedaT { get; set; }
public ImageView Art { get; set; }
public Button buttonMax { get; set; }
public Button buttonMin { get; set; }
public ImageButton buttonDel { get; set; }
}
}
enter image description here
enter image description here
I hope you can guide me the way to follow, thanks for your time.
Yes, you can use event to achieve this just as ToolmakerSteve mentioned.
I made a simple demo to pass a int parameter to the main page, you can refer to the following code:
1.in your Adapter,define variable MyEvent:
public class WishAdapter : BaseAdapter<EN_WishDetalle>
{
// add EventHandler here
public event EventHandler<int> MyEvent;
//other code
public WishAdapter(Context context, List<EN_WishDetalle> list)
{
sList = list;
sContext = context;
}
//other code
}
2.in method GetView of class WishAdapter , add code for button buttonMax:
holder.buttonMax.Click += delegate
{
// other code
// invoke here
MyEvent?.Invoke(this, 1);
};
3.In WishFragment,do like this:
adapter = new WishAdapter(Activity, List_Wish);
WishlistView.Adapter = adapter;
adapter.MyEvent += Adapter_MyEvent;
And method Adapter_MyEvent is:
private void Adapter_MyEvent(object sender, int e)
{ // here we can get the passed parameter e
Debug.WriteLine("The passed parameter : " + e);
}

UI bug while updating recycler view

I'm using FirebaseUI FirestorePagingAdapter for recycler view adapter and the recycler view uses GridLayout type with 2 columns . The recycler view item block cantains 1 image view and few others textView , when I scroll down the list and scroll back up top the image view size decreases , this bug continues every time I scroll down and back up .
It also happens when I update the adapter .
Below is the code for it . Btw I'm using Navigation Component UI.
private FirestorePagingAdapter<ProductModel, HomePagingHolder> pagingAdapter;
private FirestorePagingOptions<ProductModel> pagingOptions;
private final PagingConfig config = new PagingConfig(15, 10, false);
POJO class
public class ProductModel {
private boolean availability;
private DocumentReference category_reference;
private boolean customizable;
private String delivery_fee;
private String description;
private String max_order_quantity;
private String name;
private String price;
private List<String> thumbnails;
private String productID;
public ProductModel(){}
public ProductModel(boolean availability, DocumentReference category_reference, boolean customizable,
String delivery_fee, String description, String max_order_quantity, String name, String price, List<String> thumbnails) {
this.availability = availability;
this.category_reference = category_reference;
this.customizable = customizable;
this.delivery_fee = delivery_fee;
this.description = description;
this.max_order_quantity = max_order_quantity;
this.name = name;
this.price = price;
this.thumbnails = thumbnails;
}
public boolean isAvailability() {
return availability;
}
public void setAvailability(boolean availability) {
this.availability = availability;
}
public DocumentReference getCategory_reference() {
return category_reference;
}
public void setCategory_reference(DocumentReference category_reference) {
this.category_reference = category_reference;
}
public String getProductID() {
return productID;
}
public void setProductID(String productID) {
this.productID = productID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public boolean isCustomizable() {
return customizable;
}
public void setCustomizable(boolean customizable) {
this.customizable = customizable;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
public String getMax_order_quantity() {
return max_order_quantity;
}
public void setMax_order_quantity(String max_order_quantity) {
this.max_order_quantity = max_order_quantity;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public List<String> getThumbnails() {
return thumbnails;
}
public void setThumbnails( List<String> thumbnails) {
this.thumbnails = thumbnails;
}
}
ViewHolder class
static class HomePagingHolder extends RecyclerView.ViewHolder {
private final TextView pName;
private final TextView pPrice;
private final ImageView pImg;
private final TextView pThumbnailCount;
public HomePagingHolder(#NonNull View itemView) {
super(itemView);
pName = itemView.findViewById(R.id.productName);
pPrice = itemView.findViewById(R.id.productPrice);
pImg = itemView.findViewById(R.id.productImg);
pThumbnailCount = itemView.findViewById(R.id.thumbnail_count_txt);
}
}
Inside the Fragment
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
...
...
if (pagingOptions == null) {
getProductFromFireStore(false);
initFirestoreUIAdapter();
}
}
Getting the data
private void getProductFromFireStore(boolean check) {
pagingOptions = new FirestorePagingOptions.Builder<ProductModel>().setLifecycleOwner(this).setQuery(productCollection,
config, snapshot -> {
ProductModel model = snapshot.toObject(ProductModel.class);
if (model != null) {
model.setProductID(snapshot.getId());
}
return Objects.requireNonNull(model);
}).build();
if (check) {
pagingAdapter.updateOptions(pagingOptions);
}
}
productCollection inside the setQuery(...) points to a Collection reference inside Firestore.
Adapter
private void initFirestoreUIAdapter() {
pagingAdapter = new FirestorePagingAdapter<ProductModel, HomePagingHolder>(pagingOptions) {
#Override
protected void onBindViewHolder(#NonNull HomePagingHolder holder, int position, #NonNull ProductModel model) {
holder.pName.setText(model.getName());
holder.pPrice.setText(String.format("%s %s", getResources().getString(R.string.rupee_symbol), model.getPrice()));
holder.pThumbnailCount.setText(String.valueOf(model.getThumbnails().size()));
Glide.with(requireContext()).load(model.getThumbnails().get(0)).into(holder.pImg);
holder.itemView.setOnClickListener(view -> {
bundle.putString(Fire.FIELD_PRODUCT_ID, model.getProductID());
NavHostFragment.findNavController(HomeFragment.this).navigate(R.id.action_home_to_productFragment2, bundle);
});
}
#NonNull
#Override
public HomePagingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(requireContext()).inflate(R.layout.block_home_product_item, parent, false);
return new HomePagingHolder(v);
}
};
}
Recycler view item block
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/product_item_ripple"
android:clickable="true"
android:focusable="true">
<com.google.android.material.card.MaterialCardView
android:id="#+id/imgCard"
android:layout_width="180dp"
android:layout_height="220dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:cardBackgroundColor="#color/colorSurface"
app:cardCornerRadius="8dp"
app:cardElevation="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
app:cardCornerRadius="8dp"
app:cardElevation="0dp">
<ImageView
android:id="#+id/productImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="#color/colorSurface"
android:src="#drawable/log_in_lounge_bg"
tools:ignore="ContentDescription" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/thumbnail_count_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/white_txt_bg"
android:drawablePadding="4dp"
android:elevation="4dp"
android:fontFamily="#font/nunito"
android:text="3"
app:drawableEndCompat="#drawable/ic_multiple_image" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:id="#+id/productName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ellipsize="end"
android:fontFamily="#font/montserrat"
android:maxLines="2"
android:text="Arm chair blue color"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="#+id/imgCard"
app:layout_constraintStart_toStartOf="#+id/imgCard"
app:layout_constraintTop_toBottomOf="#+id/imgCard" />
<TextView
android:id="#+id/productPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/nunito"
android:text="TextView"
android:textColor="#color/colorTextMini"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/productName"
app:layout_constraintStart_toStartOf="#+id/productName"
app:layout_constraintTop_toBottomOf="#+id/productName" />
</androidx.constraintlayout.widget.ConstraintLayout>
Item block
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/product_item_ripple"
android:clickable="true"
android:focusable="true">
<com.google.android.material.card.MaterialCardView
android:id="#+id/imgCard"
android:layout_width="180dp"
android:layout_height="220dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:cardBackgroundColor="#color/colorSurface"
app:cardCornerRadius="8dp"
app:cardElevation="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/productImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_centerInParent="true"
android:background="#color/colorSurface"
android:src="#drawable/log_in_lounge_bg"
app:shapeAppearance="#style/IsthmusShapeableImageStyle"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/thumbnail_count_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/white_txt_bg"
android:drawablePadding="4dp"
android:elevation="4dp"
android:fontFamily="#font/nunito"
tools:text="3"
app:drawableEndCompat="#drawable/ic_multiple_image" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:id="#+id/productName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ellipsize="end"
android:fontFamily="#font/montserrat"
android:maxLines="2"
tools:text="Arm chair blue color"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="#+id/imgCard"
app:layout_constraintStart_toStartOf="#+id/imgCard"
app:layout_constraintTop_toBottomOf="#+id/imgCard" />
<TextView
android:id="#+id/productPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/nunito"
tools:text="TextView"
android:textColor="#color/colorTextMini"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/productName"
app:layout_constraintStart_toStartOf="#+id/productName"
app:layout_constraintTop_toBottomOf="#+id/productName" />
</androidx.constraintlayout.widget.ConstraintLayout>

I am trying to display data from server to Recycler View but getting error

I have made a recyclerview and populating it with data from server with volley, but this error keep coming back, I have tried all the solutions available but it won't work. Some help will be really appreciated.
I am using MySQL database my api for getting data from database is working fine, but recyclerview is giving this error
"android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText"
Data Class:
public class bus_data {
private int id;
private String bus_number;
private String bus_total_seats;
private String bus_available_seats;
private String bus_route;
private String bus_leaving_time;
private String bus_reaching_time;
private String bus_driver_name;
private String bus_ticketchecker_name;
private String bus_rating;
private String bus_break_time;
private String bus_company;
public bus_data(int id,String bus_number,String bus_total_seats,String bus_available_seats,
String bus_route,String bus_leaving_time,String bus_reaching_time,
String bus_driver_name,String bus_ticketchecker_name,String bus_rating,String bus_break_time,String bus_company) {
this.id = id;
this.bus_number = bus_number;
this.bus_total_seats = bus_total_seats;
this.bus_available_seats = bus_available_seats;
this.bus_route = bus_route;
this.bus_leaving_time = bus_leaving_time;
this.bus_reaching_time = bus_reaching_time;
this.bus_driver_name = bus_driver_name;
this.bus_ticketchecker_name = bus_ticketchecker_name;
this.bus_rating = bus_rating;
this.bus_break_time = bus_break_time;
this.bus_company = bus_company;
}
public int getId() {
return id;
}
public String getbus_number() {
return bus_number;
}
public String getbus_total_seats() {
return bus_total_seats;
}
public String getbus_available_seats() {
return bus_available_seats;
}
public String getbus_route() {
return bus_route;
}
public String getbus_leaving_time() {
return bus_leaving_time;
}
public String getbus_reaching_time() {
return bus_reaching_time;
}
public String getbus_driver_name() {
return bus_driver_name;
}
public String getbus_ticketchecker_name() {
return bus_ticketchecker_name;
}
public String getbus_rating() {
return bus_rating;
}
public String getbus_break_time() {
return bus_break_time;
}
public String getbus_company() {
return bus_company;
}
}
Adapter Class:
public class adapter_class extends RecyclerView.Adapter<adapter_class.bus_dataViewHolder> {
private Context mCtx;
private List<bus_data> productList;
public adapter_class(Context mCtx, List<bus_data> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public bus_dataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.bus_detail_list, null);
return new bus_dataViewHolder(view);
}
#Override
public void onBindViewHolder(bus_dataViewHolder holder, int position) {
bus_data busDetail = productList.get(position);
//loading the image
holder.bus_number.setText(busDetail.getbus_number());
holder.total_seats.setText(busDetail.getbus_total_seats());
holder.available_seats.setText(String.valueOf(busDetail.getbus_available_seats()));
holder.bus_route.setText(String.valueOf(busDetail.getbus_route()));
holder.bus_leaving_time.setText(String.valueOf(busDetail.getbus_leaving_time()));
holder.bus_reaching_time.setText(String.valueOf(busDetail.getbus_reaching_time()));
holder.bus_driver_name.setText(String.valueOf(busDetail.getbus_driver_name()));
holder.bus_ticketchecker_name.setText(String.valueOf(busDetail.getbus_ticketchecker_name()));
holder.bus_rating.setText(String.valueOf(busDetail.getbus_rating()));
holder.bus_break_time.setText(String.valueOf(busDetail.getbus_break_time()));
holder.bus_company.setText(String.valueOf(busDetail.getbus_company()));
}
#Override
public int getItemCount() {
return productList.size();
}
class bus_dataViewHolder extends RecyclerView.ViewHolder {
EditText bus_number, total_seats, available_seats, bus_route, bus_leaving_time, bus_reaching_time,
bus_driver_name, bus_ticketchecker_name, bus_rating, bus_break_time, bus_company;
public bus_dataViewHolder(View itemView) {
super(itemView);
bus_number = itemView.findViewById(R.id.bus_number);
total_seats = itemView.findViewById(R.id.total_seats);
available_seats = itemView.findViewById(R.id.available_seats);
bus_route = itemView.findViewById(R.id.route);
bus_leaving_time = itemView.findViewById(R.id.leaving_time);
bus_reaching_time = itemView.findViewById(R.id.reaching_time);
bus_driver_name = itemView.findViewById(R.id.driver_name);
bus_ticketchecker_name = itemView.findViewById(R.id.tk_checker_name);
bus_rating = itemView.findViewById(R.id.rating);
bus_break_time = itemView.findViewById(R.id.break_time);
bus_company = itemView.findViewById(R.id.bus_company);
}
}
}
Main Class:
public class Bus_Details extends AppCompatActivity {
private static final String URL_PRODUCTS = "http://192.168.10.17/AutoBus/api.php";
//a list to store all the products
List<bus_data> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bus_details);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
recyclerView = findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject data = array.getJSONObject(i);
//adding the product to product list
productList.add(new bus_data(
data.getInt("id"),
data.getString("bus_number"),
data.getString("bus_total_seats"),
data.getString("bus_available_seats"),
data.getString("bus_route"),
data.getString("bus_leaving_time"),
data.getString("bus_reaching_time"),
data.getString("bus_driver_name"),
data.getString("bus_ticketchecker_name"),
data.getString("bus_rating"),
data.getString("bus_break_time"),
data.getString("bus_company")
));
}
//creating adapter object and setting it to recyclerview
adapter_class adapter = new adapter_class(Bus_Details.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Bus_Details.this, "Error"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Bus_Details.this, "Error"+error.toString(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
}
Here are the layout files.
recycler_activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Passenger.Bus_Details">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="-51dp" />
</RelativeLayout>
List_activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:id="#+id/layout">
<TextView
android:id="#+id/bus_company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Daewo"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#ffffff" />
<TextView
android:id="#+id/bus_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bus_company"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="GJN-1234"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/total_seats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bus_number"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:background="#color/colorPrimary"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="70"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/available_seats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/total_seats"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/leaving_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/available_seats"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/reaching_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/leaving_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/driver_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/reaching_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/tk_checker_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/driver_name"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/break_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tk_checker_name"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/break_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/route"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rating"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
This is the error I am getting
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.autobus, PID: 10266
java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText
Screenshot of error:
In your bus_dataViewHolder class replace EditText to TextView.
because in layout you can use TextView and inside the program you use Edittext, that's while this issue generated.
This issue is because you take TextView in your adapter xml and get it like as a EditText.
So change in your adapter onCreateViewHolder from EditText to TextView .
Change below line in your adapter class.
TextView bus_number, total_seats, available_seats, bus_route, bus_leaving_time, bus_reaching_time,
bus_driver_name, bus_ticketchecker_name, bus_rating, bus_break_time, bus_company;

Why does my RecyclerView contain only 1 item?

I am creating a weather forecast aplication. For this I want to use RecyclerView to show items. The problem is that my RecyclerView is showing only one item instead of all. I am using the OpenWeatherMap API forecast.
This is my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/weather_background2"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txt_close_weather"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="#drawable/circle"
android:gravity="center"
android:text="X"
android:textColor="#color/blackTransparent"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:orientation="vertical">
<TextView
android:id="#+id/city_country_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="0dp"
android:text="KOTA"
android:textColor="#color/blackTransparent"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:text="Today"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<TextView
android:id="#+id/current_date_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<ImageView
android:id="#+id/weather_icon"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_gravity="center|center_horizontal"
android:layout_marginTop="8dp"
android:contentDescription="#string/app_name"
android:src="#drawable/img_02d" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="3">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hummidity"
android:textColor="#color/blackTransparent"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/wind_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="14dp" />
<TextView
android:id="#+id/temperature_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:background="#color/whiteTr"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2.5"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/weather_daily_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:scrollbars="none" />
</LinearLayout>
</LinearLayout>
This my code in activity :
public class DialogWeather extends android.app.DialogFragment {
public static final int WIDTH = 60;
public static final int HEIGHT = 80;
public static final String DATE_FORMAT_WITHOUT_TIME = "dd/MM";
private static final String ICON_PREFIX = "img_";
private static final String API_KEY = "2fc56d498a3b4d87ba298c232e65e6b0";
private static final String UNITS = "metric";
final String q = "Jakarta";
PopupWindow myPopupWindow;
Dialog myDialog;
DialogWeather dialogWeather;
private TextView txtCloseWeather, txtCityCountry,
txtCurrentDate, tvDescription, tvWindResult, tvTemperatureResult;
private ImageView weatherIcon;
private RecyclerView mRecyclerViewWeather;
DialogWeatherAdapter dialogWeatherAdapter;
private ArrayList<Example2> weathers = new ArrayList<>();
Example2 example2List;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_dialog_weather,
container, false);
getDialog().getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
tvDescription = rootView.findViewById(R.id.tv_description);
tvWindResult = rootView.findViewById(R.id.wind_result);
tvTemperatureResult = rootView.findViewById(R.id.temperature_result);
weatherIcon = rootView.findViewById(R.id.weather_icon);
txtCityCountry = rootView.findViewById(R.id.city_country_weather);
txtCityCountry.setTypeface(Typeface.DEFAULT_BOLD);
txtCurrentDate = rootView.findViewById(R.id.current_date_weather);
txtCloseWeather = rootView.findViewById(R.id.txt_close_weather);
txtCloseWeather.setTypeface(Typeface.DEFAULT_BOLD);
Fragment fragment = this;
txtCloseWeather.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Close",
Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().beginTransaction()
.remove(fragment).commit();
}
});
mRecyclerViewWeather = rootView.findViewById(R.id.weather_daily_list);
LinearLayoutManager layoutManager = new
LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRecyclerViewWeather.setLayoutManager(layoutManager);
mRecyclerViewWeather.setHasFixedSize(true);
dialogWeatherAdapter = new DialogWeatherAdapter(weathers);
mRecyclerViewWeather.setAdapter(dialogWeatherAdapter);
loadWeathers(q, API_KEY, UNITS);
return rootView;
}
private void loadWeathers(String q, String apiKey, String units) {
ApiServicesWeather weather = InitRetrofitWeather.getServicesWeather();
Call<Example2> exampleCall = weather.getDetailWeather(q, apiKey, units);
exampleCall.enqueue(new Callback<Example2>() {
#Override
public void onResponse(Call<Example2> call, Response<Example2>
response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_LONG).show();
example2List = response.body();
weathers.addAll(Collections.singleton(example2List));
loadSetView();
dialogWeatherAdapter.updateList(weathers);
dialogWeatherAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Example2> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Gagal " +
t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void loadSetView() {
txtCityCountry.setText(weathers.get(getId()).getCity().getName());
txtCurrentDate.setText(Util.formatDate(weathers
.get(getId()).getList().get(getId()).getDtTxt(), "EEE MMM dd, yyyy"));
weatherIcon.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(),ICON_PREFIX + weathers
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
tvDescription.setText(weathers.get(getId()).getList().get(getId())
.getWeather().get(getId()).getDescription());
tvWindResult.setText("Wind : " +
weathers.get(getId()).getList().get(getId()).getWind().getSpeed() + " m/s");
double mTemperature = (double)
weathers.get(getId()).getList().get(getId()).getMain().getTemp();
tvTemperatureResult.setText(String.valueOf(weathers
.get(getId()).getList().get(ge
tId()).getMain().getTemp()) + " °C");
}
#Override
public void onResume() {
super.onResume();
ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = 700;
params.height = 1100;
getDialog().getWindow().setAttributes((WindowManager.LayoutParams)
params);
}
this My Adapter :
public class DialogWeatherAdapter extends
RecyclerView.Adapter<DialogWeatherAdapter.DialogViewHolder> {
ArrayList<Example2> data;
Context context;
Activity c;
public DialogWeatherAdapter(ArrayList<Example2> data, Context context,
Activity c) {
this.data = data;
this.context = context;
this.c = c;
}
public DialogWeatherAdapter(ArrayList<Example2> weathers) {
this.data = weathers;
}
#Override
public DialogViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater = (LayoutInflater)
parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.item_weathers, parent,
false);
return new DialogViewHolder(view);
}
#Override
public void onBindViewHolder(DialogViewHolder holder, int position) {
if (holder instanceof DialogViewHolder) {
final DialogViewHolder viewHolder = (DialogViewHolder) holder;
if (data != null) {
for (int i = 0; i < data.size(); i++) {
viewHolder.tvCurrentDateItem.setText(Util.formatDate(data
.get(position).getList()
.get(position).getDtTxt(), "dd/MM"));
viewHolder.ivIconItem.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(), ICON_PREFIX + data
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
viewHolder.tvDescriptionItem.setText(data.get(position)
.getList().get(position).getWeather().get(position).getDescription());
viewHolder.tvTemperatureItem.setText(String.valueOf(weathers
.get(getId()).getList
().get(getId()).getMain().getTemp()) + " °C");
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public void updateList(ArrayList<Example2> weathers) {
this.data = weathers;
}
public class DialogViewHolder extends RecyclerView.ViewHolder {
TextView tvCurrentDateItem, tvDescriptionItem, tvTemperatureItem;
ImageView ivIconItem;
public DialogViewHolder(View itemView) {
super(itemView);
tvCurrentDateItem = itemView.findViewById(R.id.current_date_weather_item);
tvDescriptionItem = itemView.findViewById(R.id.description_item);
tvTemperatureItem = itemView.findViewById(R.id.temperature_item);
ivIconItem = itemView.findViewById(R.id.icon_weather_item);
}
}
}
enter image description here
The reason for this is -
The Item file (R.layout.item_weathers) has height match parent. Change it to wrap_content as shown -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and it will show all the items.

Listview returning the wrong postion with BaseSwipeAdapter

I am using a listview with swipelayout (daimajia library) and my listview is scrolling...
My problem is when I swipe listview item and click on button in it ,it returns me wrong position..
Do you have any idea of how to solve this??
This is my adapter
public View generateView(final int position, final ViewGroup parent) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, null);
SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(getSwipeLayoutResourceId(position));
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
}
});
swipeLayout.setOnDoubleClickListener(new
SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(context, "DoubleClick",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
I think your implementation of getView method is messy. Try this.
ListAdapter Java class.
package com.dev4solutions.myapplication.activities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SimpleSwipeListener;
import com.daimajia.swipe.SwipeLayout;
import com.dev4solutions.myapplication.R;
import java.util.ArrayList;
class ListAdapter extends BaseAdapter {
private ArrayList<String> strings;
private Context mContext;
public ListAdapter(Context context, ArrayList<String> list) {
strings = list;
mContext = context;
}
#Override
public int getCount() {
return strings.size();
}
#Override
public Object getItem(int i) {
return strings.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.ledger_layout, null);
viewHolder = new ViewHolder();
viewHolder.swipeLayout = view.findViewById(R.id.swipe);
viewHolder.textView = view.findViewById(R.id.text_data);
viewHolder.delete = view.findViewById(R.id.delete);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.textView.setText(String.valueOf("Swipe Layout : " + position));
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
Toast.makeText(mContext, "onOpen : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "onDelete Click : " + position,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
// view holder for managing to recycle of view
public static class ViewHolder {
SwipeLayout swipeLayout;
TextView textView;
View delete;
}
}
ledger_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#FF5534"
android:gravity="center"
android:tag="Bottom3"
android:weightSum="10">
<ImageView
android:id="#+id/trash"
android:layout_width="27dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="#android:drawable/ic_delete" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="Delete Item?"
android:textColor="#fff"
android:textSize="17sp" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="4"
android:background="#ffffff"
android:text="Yes,Delete"
android:textColor="#FF5534" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cac6c6"
android:padding="10dp">
<TextView
android:id="#+id/position"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:tag="Hover"
android:text="Do not, for one repulse, forgo the purpose that you resolved to effort. " />
</LinearLayout>
</com.daimajia.swipe.SwipeLayout>
using the way which is marked as an answer will work but there is an another way of doing it too...
adapter class
public class testadapter1 extends RecyclerSwipeAdapter<testadapter1.SimpleViewHolder> {
public static final String TAG = testadapter1.class.getSimpleName();
private static SwipLayoutListener swipLayoutListener;
private static ClickListener clickListener;
String[] time;
Animation animSlide;
boolean ANIM_FLAG = true;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
private int visibleThreshold = 5;
private String phone;
private String email;
public static class SimpleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
SwipeLayout swipeLayout;
TextView text;
TextView info;
TextView swipeImage;
LinearLayout linearLayout;
ImageView imageView;
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
Log.e("position", String.valueOf(getAdapterPosition()));
}
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
text = (TextView) itemView.findViewById(R.id.input_cname);
txtdate = (TextView) itemView.findViewById(R.id.date);
id = (TextView) itemView.findViewById(R.id.input_cid);
Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
FontManager.markAsIconContainer(itemView.findViewById(R.id.swipe), iconFont);
swipeImage = itemView.findViewById(R.id.swipeIcon);
imageView = new ImageView(mContext);
call = (TextView) itemView.findViewById(R.id.call_btn);
sms = (TextView) itemView.findViewById(R.id.sms_btn);
mail = (TextView) itemView.findViewById(R.id.email_btn);
info = (TextView) itemView.findViewById(R.id.detail_btn);
call.setTypeface(iconFont);
sms.setTypeface(iconFont);
mail.setTypeface(iconFont);
info.setTypeface(iconFont);
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, linearLayout);
itemView.setOnClickListener(this);
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
if (swipLayoutListener != null) {
swipLayoutListener.onOpen(layout, getAdapterPosition());
}
}
});
}
}
private static Context mContext;
ArrayList<HashMap<String, String>> mDataset;
public testadapter1(Context mContext, ArrayList<HashMap<String, String>> objects, RecyclerView listView) {
this.mContext = mContext;
this.mDataset = objects;
if (listView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) listView
.getLayoutManager();
listView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView listView,
int dx, int dy) {
super.onScrolled(listView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, parent, false);
return new SimpleViewHolder(view);
}
public interface ClickListener {
void onItemClick(int position, View v);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
viewHolder.txtdate.setText(mDataset.get(position).get("date"));
viewHolder.id.setText("Amount: ₹ " + viewHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// HashMap<String, String> mDataset = getItem1(position);
Intent intent = new Intent(mContext, LedgerDetailActivity.class);
intent.putExtra("ledger_name", String.valueOf(mDataset.get(position).get("ledger_name")));
// Log.e("intent", mDataset.get("ledger_name"));
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
if (mDataset == null) {
Log.d(TAG, "getCount: 0");
return 0;
} else {
Log.d(TAG, "getCount: " + mDataset.size());
return mDataset.size();
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
public void addSwipeListener(SwipLayoutListener swipLayoutListener) {
testadapter1.swipLayoutListener = swipLayoutListener;
}
public interface SwipLayoutListener {
void onOpen(SwipeLayout layout, int position);
}
fragment layout
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/frame3"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/list_ledger"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"/>
<!-- Adding bottom sheet after main content -->
</android.support.v4.widget.SwipeRefreshLayout>
adapter layout
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center"
android:weightSum="7">
<RelativeLayout
android:id="#+id/relativeLayoutSms"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/call_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_phone"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/call_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Call"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutCall"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/sms_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_sms"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sms_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="SMS"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutMail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/email_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_mail"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/email_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Email"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/detail_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_info"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/detail_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Details"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:id="#+id/input_cname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/date"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#id/amount"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#color/colorAccent"
android:textSize="16sp" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/input_cname"
android:layout_marginStart="10dp"
android:paddingTop="2dp"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/input_cid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="2dp"
android:layout_marginStart="10dp"
android:paddingEnd="5dp"
android:textAlignment="viewEnd"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/gp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/input_cid"
android:layout_below="#+id/input_cname"
android:textAlignment="viewEnd"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="14sp"
android:visibility="gone" />
<TextView
android:id="#+id/swipeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#id/gp"
android:layout_marginTop="14dp"
android:paddingStart="6dp"
android:visibility="gone" />
</RelativeLayout>
It's been a long time but I had the same issue. It took hours to solve the problem but the solution is here. This WARNING is from the daimajia's wiki.
ATTENTION: Never bind listeners or fill values in generateView. Just generate the view and do everything else in fillValues (e.g using your holder class) See issues #14 and #17
You can find detailed solution here : Solution to your position problem from daimajia's wiki
And sample code is like this :
//ATTENTION: Never bind listener or fill values in generateView.
// You have to do that in fillValues method.
#Override
public View generateView(int position, ViewGroup parent) {
return LayoutInflater.from(mContext).inflate(R.layout.grid_item, null);
}
#Override
public void fillValues(int position, View convertView) {
TextView t = (TextView)convertView.findViewById(R.id.position);
t.setText((position + 1 )+".");
}
You should do everything in fillValues() function. position value here is always right.
Just follow this rule and everything will be fine with your Swipe ListView.

Categories

Resources