Modify textview of parent layout from adapter xamarin android - 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);
}

Related

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.

Click event not working for Recyclerview item with SwipeLayout in Xamarin Android

I setup a recyclerview with a viewholder with a click event on the recyclerview items, following the guide at https://developer.xamarin.com/guides/android/user_interface/recyclerview/
and everything worked just fine.
After that, i wanted to use this component for the swipe feature
https://components.xamarin.com/view/androidswipelayout
the swipe if working fine, but the click on the recyclerview item doens't trigger the event anymore. Any suggestions?
The itemlayout is
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.daimajia.swipe.SwipeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/swipe_layout"
android:clickable="false"
android:focusable="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF5534"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Elimina"
android:layout_marginLeft="30dp"
android:textColor="#fff"
android:textSize="17sp" />
<View
android:layout_height="wrap_content"
android:layout_width="0px"
android:layout_weight="1" />
<ImageView
android:id="#+id/trash"
android:layout_width="36dp"
android:layout_height="40dp"
android:layout_marginRight="50dp"
android:src="#drawable/trash" />
</LinearLayout>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="4dp"
app:cardUseCompatPadding="true"
app:cardCornerRadius="3dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_margin="3dp"
android:id="#+id/imageView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:lines="1"
android:maxLines="1"
android:ellipsize="end" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/author"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/fairNav"
android:id="#+id/progress"
android:layout_alignBottom="#+id/imageView"
android:layout_alignRight="#+id/imageView"
android:layout_gravity="bottom"
android:layout_margin="7dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</com.daimajia.swipe.SwipeLayout>
</FrameLayout>
the adapter:
public class BookCardAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler ItemClick;
List<LibraryEdition> items;
Context mContext {get; set;}
public BookCardAdapter(List<LibraryEdition> myDataset, Context context) {
items = myDataset;
mContext = context;
}
public override RecyclerView.ViewHolder OnCreateViewHolder (ViewGroup parent, int viewType)
{
// Inflate the CardView for the photo:
View itemView = LayoutInflater.From (parent.Context).
Inflate (Resource.Layout.CardBookListItem, parent, false);
BookCardViewHolder vh = new BookCardViewHolder (itemView, OnClick);
vh.Icon.Click += (object senerObj, EventArgs eve) => {
AndroidUtils.ReadList.Delete (items [vh.AdapterPosition].EditionID);
FairbooksAPI.DeleteFromReadingList (items [vh.AdapterPosition].VersionID);
items.RemoveAt (vh.AdapterPosition);
NotifyItemRemoved (vh.AdapterPosition);
NotifyItemRangeChanged (vh.AdapterPosition, items.Count);
vh.SwipeLayout.Close (true);
AndroidUtils.toUpdateHomeReadings = true;
};
vh.SwipeLayout.SetShowMode (SwipeLayout.ShowMode.LayDown);
vh.SwipeLayout.Opened += (sender, e) => {
YoYo.With (Techniques.Tada)
.Duration (700)
.PlayOn (vh.Icon);
};
return vh;
}
// Fill in the contents of the book (invoked by the layout manager):
public override void OnBindViewHolder (RecyclerView.ViewHolder holder, int position)
{
BookCardViewHolder vh = holder as BookCardViewHolder;
vh.Image.SetImageBitmap(null);
string coverUrl = items[position].CoverUrl;
AndroidUtils.SetImage (mContext, coverUrl, vh.Image);
vh.Title.Text = items[position].Title;
vh.Author.Text = "by " + items [position].Author.UserName;
int value = (int)items [position].Percentage;
vh.Progress.Text = value > 100 ? "100%" : value + "%";
}
// Return the number of books:
public override int ItemCount
{
get { return items.Count; }
}
// Raise an event when the item-click takes place:
void OnClick (int position)
{
if (ItemClick != null)
ItemClick (this, position);
}
}
the viewholder:
public class BookCardViewHolder : RecyclerView.ViewHolder
{
public SwipeLayout SwipeLayout;
public ImageView Icon;
public ImageView Image { get; private set; }
public TextView Title { get; private set; }
public TextView Author { get; private set; }
public TextView Progress { get; private set; }
public BookCardViewHolder (View itemView, Action<int> listener)
: base (itemView)
{
SwipeLayout = itemView.FindViewById<SwipeLayout> (Resource.Id.swipe_layout);
Icon = itemView.FindViewById<ImageView> (Resource.Id.trash);
Image = itemView.FindViewById<ImageView> (Resource.Id.imageView);
Title = itemView.FindViewById<TextView> (Resource.Id.title);
Author = itemView.FindViewById<TextView> (Resource.Id.author);
Progress = itemView.FindViewById<TextView> (Resource.Id.progress);
itemView.Click += (sender, e) => listener (base.AdapterPosition);
}
}
and in the parent fragment i set the adapter like this:
mAdapter = new BookCardAdapter (Books, this.Activity);
// Register the item click handler (below) with the adapter:
mAdapter.ItemClick += OnItemClick;
mRecyclerView.SetAdapter (mAdapter);
and:
void OnItemClick (object sender, int position)
{
// ProgressDialog progress = new ProgressDialog (this.Activity);
// progress.SetMessage ("Opening Book...");
// progress.Show ();
AndroidUtils.Read (Books [position], this.Activity);
}

ViewPager Activity change content when slide

I've been looking around but I can't figure out how I can fixed this issue.
I'm using the #Dave Morrissey's Subsampling Zoom Image View, is a great library and it works perfect, but I want to do a few changes.
For each image that the user will slide I want show the specific description.
So it will be:
Pic1 |Pic2 |Pic3
DescriptionPic1 |DescriptionPic2 |DescriptionPic3
When I open it I can see the picture with below the right description but when I slide left(or right) I can see always the description of the item after.
Happens because the method getItem() get called twice to make the slider more smooth.
The problem is that I want show the right content(description) below each picture.
How can I show the content perfectly when the user slide the pics?
Any help is really appreciate.
Thanks guys
ViewPagerActivity.java
public class ViewPagerActivity extends FragmentActivity {
private ViewPager page;
private Bitmap bmImg1;
private Bitmap bmImg2;
private Bitmap bmImg3;
private String TAG;
ArrayList<Bitmap> IMAGES =new ArrayList<Bitmap>();
String[] descriptionPhoto;
int numpics=1;
private int position_pic;
private String suggested_aperture;
private String suggested_filter;
private String suggested_iso;
private String suggested_shutter;
private String suggested_shot_level;
private String suggested_lens;
private String[] shot_levelPhoto;
private String[] filterPhoto;
private String[] aperturePhoto;
private String[] shutterPhoto;
private String[] isoPhoto;
private String[] focal_lengthPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
FileInputStream fis;
FileInputStream fis2;
FileInputStream fis3;
Bundle intent=getIntent().getExtras();
descriptionPhoto = intent.getStringArray("descriptionPhoto");
numpics = (int) intent.get("numpics");
position_pic = (int) intent.get("position_pic");
suggested_aperture= intent.getString("suggested_aperture");
suggested_filter= intent.getString("suggested_filter");
suggested_iso= intent.getString("suggested_iso");
suggested_shutter= intent.getString("suggested_shutter");
suggested_shot_level= intent.getString("suggested_shot_level");
suggested_lens= intent.getString("suggested_lens");
shot_levelPhoto=intent.getStringArray("shot_levelPhoto");
filterPhoto =intent.getStringArray("filterPhoto");
aperturePhoto =intent.getStringArray("aperturePhoto");
shutterPhoto =intent.getStringArray("shutterPhoto");
isoPhoto =intent.getStringArray("isoPhoto");
focal_lengthPhoto=intent.getStringArray("focal_lengthPhoto");
TextView txtaperture_suggested = (TextView) findViewById(R.id.aperture_suggested);
TextView txtfilter_suggested = (TextView) findViewById(R.id.filter_suggested);
TextView txtiso_suggested = (TextView) findViewById(R.id.iso_suggested);
TextView txtlens_suggested = (TextView) findViewById(R.id.lens_suggested);
TextView txtshutter_suggested = (TextView) findViewById(R.id.shutter_suggested);
TextView txtshot_levelsuggested = (TextView) findViewById(R.id.shot_levelsuggested);
if (suggested_shot_level == "1") {
txtshot_levelsuggested.setText("Easy");
/*txtshot_levelPhoto2.setText("Easy");
txtshot_levelPhoto3.setText("Easy");*/
} else if (suggested_shot_level == "2") {
txtshot_levelsuggested.setText("Medium");
/* txtshot_levelPhoto2.setText("Medium");
txtshot_levelPhoto3.setText("Medium");*/
} else if (suggested_shot_level == "3") {
txtshot_levelsuggested.setText("Difficult");
/*txtshot_levelPhoto2.setText("Difficult");
txtshot_levelPhoto3.setText("Difficult");*/
} else {
txtshot_levelsuggested.setText("Pro");
/* txtshot_levelPhoto2.setText("Pro");
txtshot_levelPhoto3.setText("Pro");*/
}
txtaperture_suggested.setText(suggested_aperture);
txtfilter_suggested.setText(suggested_filter);
txtiso_suggested.setText(suggested_iso);
txtshutter_suggested.setText(suggested_shutter);
txtlens_suggested.setText(suggested_lens);
TextView txtshutterPhoto = (TextView) findViewById(R.id.shutterPhoto);
TextView txtshutterPhoto2 = (TextView) findViewById(R.id.shutterPhoto2);
TextView txtshutterPhoto3 = (TextView) findViewById(R.id.shutterPhoto3);
TextView txtshot_levelPhoto = (TextView) findViewById(R.id.shot_levelPhoto);
TextView txtshot_levelPhoto2 = (TextView) findViewById(R.id.shot_levelPhoto2);
TextView txtshot_levelPhoto3 = (TextView) findViewById(R.id.shot_levelPhoto3);
TextView txtaperturePhoto = (TextView) findViewById(R.id.aperturePhoto);
TextView txtaperturePhoto2 = (TextView) findViewById(R.id.aperturePhoto2);
TextView txtaperturePhoto3 = (TextView) findViewById(R.id.aperturePhoto3);
TextView txtfilterPhoto = (TextView) findViewById(R.id.filterPhoto);
TextView txtfilterPhoto2 = (TextView) findViewById(R.id.filterPhoto2);
TextView txtfilterPhoto3 = (TextView) findViewById(R.id.filterPhoto3);
TextView txtisoPhoto = (TextView) findViewById(R.id.isoPhoto);
TextView txtisoPhoto2 = (TextView) findViewById(R.id.isoPhoto2);
TextView txtisoPhoto3 = (TextView) findViewById(R.id.isoPhoto3);
TextView txtlensPhoto = (TextView) findViewById(R.id.lensPhoto);
TextView txtlensPhoto2 = (TextView) findViewById(R.id.lensPhoto2);
TextView txtlensPhoto3 = (TextView) findViewById(R.id.lensPhoto3);
/*txtshutterPhoto.setText(shutterPhoto[0]);
if (shutterPhoto.length > 1) {
txtshutterPhoto2.setText(shutterPhoto[1]);
if (shutterPhoto.length > 2) {
txtshutterPhoto3.setText(shutterPhoto[2]);
}
}
txtisoPhoto.setText(isoPhoto[0]);
if (isoPhoto.length > 1) {
txtisoPhoto2.setText(isoPhoto[1]);
if (isoPhoto.length > 2) {
txtisoPhoto3.setText(isoPhoto[2]);
}
}
txtfilterPhoto.setText(filterPhoto[0]);
if (filterPhoto.length > 1) {
txtfilterPhoto2.setText(filterPhoto[1]);
if ((filterPhoto.length > 2)) {
txtfilterPhoto3.setText(filterPhoto[2]);
}
}
txtaperturePhoto.setText(aperturePhoto[0]);
if (aperturePhoto.length > 1) {
txtaperturePhoto2.setText(aperturePhoto[1]);
if (aperturePhoto.length > 2) {
txtaperturePhoto3.setText(aperturePhoto[2]);
}
}*/
try {
fis = getApplicationContext().openFileInput("bmImg1");
bmImg1 = BitmapFactory.decodeStream(fis);
IMAGES.add(bmImg1);
fis.close();
/*
findViewById(R.id.note1).setVisibility(View.VISIBLE);
TextView descriptionnote = (TextView)findViewById(R.id.note1);
descriptionnote.setText(descriptionPhoto[0]);
*/
if(numpics>1){
fis2 = getApplicationContext().openFileInput("bmImg2");
bmImg2 = BitmapFactory.decodeStream(fis2);
IMAGES.add(bmImg2);
fis2.close();
/*
findViewById(R.id.note1).setVisibility(View.INVISIBLE);
findViewById(R.id.note2).setVisibility(View.VISIBLE);
TextView descriptionnote2 = (TextView)findViewById(R.id.note2);
descriptionnote2.setText(descriptionPhoto[1]);
*/
if(numpics>2){
fis3 = getApplicationContext().openFileInput("bmImg3");
bmImg3 = BitmapFactory.decodeStream(fis3);
IMAGES.add(bmImg3);
fis3.close();
/*
findViewById(R.id.note2).setVisibility(View.INVISIBLE);
findViewById(R.id.note3).setVisibility(View.VISIBLE);
TextView descriptionnote3 = (TextView)findViewById(R.id.note3);
descriptionnote3.setText(descriptionPhoto[2]);
*/
}
}
}
catch (FileNotFoundException e) {
Log.d(TAG, "file not found");
e.printStackTrace();
}
catch (IOException e) {
Log.d(TAG, "io exception");
e.printStackTrace();
}
PagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
page = (ViewPager)findViewById(R.id.pager);
page.setAdapter(pagerAdapter);
page.setCurrentItem(position_pic);
if(page.getCurrentItem()==0 ){
findViewById(R.id.note1).setVisibility(View.VISIBLE);
findViewById(R.id.note2).setVisibility(View.INVISIBLE);
findViewById(R.id.note3).setVisibility(View.INVISIBLE);
TextView descriptionnote = (TextView) findViewById(R.id.note1);
descriptionnote.setText(descriptionPhoto[0]);
}
if (page.getCurrentItem()==1 ) {
findViewById(R.id.note1).setVisibility(View.INVISIBLE);
findViewById(R.id.note2).setVisibility(View.VISIBLE);
findViewById(R.id.note3).setVisibility(View.INVISIBLE);
TextView descriptionnote2 = (TextView) findViewById(R.id.note2);
descriptionnote2.setText(descriptionPhoto[1]);
}
if (page.getCurrentItem()==2 ) {
findViewById(R.id.note1).setVisibility(View.INVISIBLE);
findViewById(R.id.note2).setVisibility(View.INVISIBLE);
findViewById(R.id.note3).setVisibility(View.VISIBLE);
TextView descriptionnote3 = (TextView) findViewById(R.id.note3);
descriptionnote3.setText(descriptionPhoto[2]);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return true;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
public int getItemPosition(Object item){
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
ViewPagerFragment fragment = new ViewPagerFragment();
fragment.setAsset(IMAGES.get(position));
return fragment;
}
#Override
public int getCount() {
return IMAGES.size();
}
}}
This is the ViewPagerFragment
public class ViewPagerFragment extends Fragment {
private static final String BUNDLE_ASSET = "res";
private Bitmap asset;
public ViewPagerFragment() {
}
public void setAsset(Bitmap asset) {
this.asset = asset;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view_pager_page, container, false);
/* if (savedInstanceState != null) {
if (asset == null && savedInstanceState.containsKey(BUNDLE_ASSET)) {
asset = savedInstanceState.getParcelable(BUNDLE_ASSET);
}
}*/
if (asset != null) {
SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)rootView.findViewById(R.id.imageView);
imageView.setImage(ImageSource.bitmap(asset));
}
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
View rootView = getView();
if (rootView != null) {
outState.putString(BUNDLE_ASSET, String.valueOf(asset));
}
}}
ViewPager.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#333">
<GridLayout
android:id="#+id/suggestedParameter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="visible"
android:paddingTop="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/textParameter"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/shot_levellabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/shot_levellabel"
android:layout_weight="0.10"
android:gravity="center"
android:layout_row="0"
android:layout_column="0"
android:textColor="#ffffff" />
<TextView
android:id="#+id/shot_levelsuggested"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:textColor="#90c683"
android:layout_weight="0.10"
android:layout_row="1"
android:layout_column="0"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/shot_levelPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="2"
android:layout_column="0"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<!-- <TextView
android:id="#+id/shot_levelPhoto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="3"
android:layout_column="0" />
<TextView
android:id="#+id/shot_levelPhoto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="4"
android:layout_column="0" />-->
<TextView
android:id="#+id/shutterPhotolabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/shutterPhotolabel"
android:layout_weight="0.10"
android:layout_row="0"
android:layout_column="1"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/shutter_suggested"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:textColor="#90c683"
android:layout_weight="0.10"
android:layout_row="1"
android:layout_column="1"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/shutterPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="2"
android:layout_column="1"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<!-- <TextView
android:id="#+id/shutterPhoto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:id="#+id/shutterPhoto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="4"
android:layout_column="1" />-->
<TextView
android:id="#+id/aperturePhotolabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/aperturePhotolabel"
android:layout_weight="0.10"
android:layout_row="0"
android:layout_column="2"
android:textColor="#ffffff" />
<TextView
android:id="#+id/aperture_suggested"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:textColor="#90c683"
android:layout_weight="0.10"
android:layout_row="1"
android:layout_column="2"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/aperturePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="2"
android:layout_column="2"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<!-- <TextView
android:id="#+id/aperturePhoto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="3"
android:layout_column="2" />
<TextView
android:id="#+id/aperturePhoto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="4"
android:layout_column="2" />-->
<TextView
android:id="#+id/isoPhotolabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/isoPhotolabel"
android:layout_weight="0.10"
android:layout_row="0"
android:layout_column="3"
android:textColor="#ffffff" />
<TextView
android:id="#+id/iso_suggested"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:textColor="#90c683"
android:layout_weight="0.10"
android:layout_row="1"
android:layout_column="3"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/isoPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center|right"
android:layout_weight="0.10"
android:paddingRight="10dp"
android:layout_row="2"
android:layout_column="3"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<!-- <TextView
android:id="#+id/isoPhoto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center|right"
android:layout_weight="0.10"
android:paddingRight="10dp"
android:layout_row="3"
android:layout_column="3" />
<TextView
android:id="#+id/isoPhoto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center|right"
android:layout_weight="0.10"
android:paddingRight="10dp"
android:layout_row="4"
android:layout_column="3" />-->
<TextView
android:id="#+id/lensPhotolabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/lensPhotolabel"
android:layout_weight="0.10"
android:layout_row="0"
android:layout_column="4"
android:textColor="#ffffff" />
<TextView
android:id="#+id/lens_suggested"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center|left"
android:textColor="#90c683"
android:layout_weight="0.10"
android:layout_row="1"
android:layout_column="4"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/lensPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="2"
android:layout_column="4"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<!-- <TextView
android:id="#+id/lensPhoto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="3"
android:layout_column="4"
/>
<TextView
android:id="#+id/lensPhoto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_weight="0.10"
android:layout_row="4"
android:layout_column="4"
/>-->
<TextView
android:id="#+id/filterPhotolabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/filterPhotolabel"
android:layout_weight="0.10"
android:layout_row="0"
android:layout_column="5"
android:textColor="#ffffff" />
<TextView
android:id="#+id/filter_suggested"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:textColor="#90c683"
android:layout_row="1"
android:layout_column="5"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/filterPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_row="2"
android:layout_column="5"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<!-- <TextView
android:id="#+id/filterPhoto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_row="3"
android:layout_column="5"
/>
<TextView
android:id="#+id/filterPhoto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint=" None"
android:gravity="center"
android:layout_row="4"
android:layout_column="5"
/>-->
</GridLayout>
<!--<TextView
android:id="#+id/parameter_suggested"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:visibility="visible"
/>
<TextView
android:id="#+id/parameter2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:visibility="invisible"
android:text="456"
android:layout_below="#+id/parameter_suggested"
/>
<TextView
android:id="#+id/parameter3"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:visibility="visible"
android:text="789"
android:layout_below="#+id/parameter_suggested"
/>
-->
</RelativeLayout>
<RelativeLayout
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#333">
<TextView
android:id="#+id/note1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:visibility="invisible"
/>
<TextView
android:id="#+id/note2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:visibility="invisible"
/>
<TextView
android:id="#+id/note3"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:visibility="invisible"
/>
</RelativeLayout>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_above="#id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/text1" />
</RelativeLayout>
you should add image into Map or Array For Reloading:
#Override
public void fill(final Picture picture, int pos, Object... objects) {
image=(ImageView) view.findViewById(R.id.img_galleryadapter_image);
caption=(TextView) view.findViewById(R.id.txt_galleryadapter_caption);
if(bitmapMap.containsKey(picture.imageUrl)){
image.setImageBitmap(bitmapMap.get(picture.imageUrl));
}else {
image.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_hourglass_empty_black_48dp));
Picasso.with(context).load(picture.imageUrl).memoryPolicy(MemoryPolicy.NO_CACHE).skipMemoryCache().into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
image.setImageBitmap(bitmap);
bitmapMap.put(picture.imageUrl, bitmap);
}
#Override
public void onBitmapFailed(Drawable drawable) {}
#Override
public void onPrepareLoad(Drawable drawable) {}
});
}
caption.setText(picture.caption);
}
add to a map:
public static Map<String,Bitmap> bitmapMap=new LinkedHashMap<>();
edit your layout in the xml file to put image then below it a textview using RelativeLayoutor once ur image and its description is aligned its upto ur java codes
After struggling and reading so many different solutions I fixed by myself the issue.
I wanted share with you my solutions maybe can help someone else.
Feel free to ask me everything about it.
This is the FragmentActivity:
public class ViewPagerActivity extends FragmentActivity {
private boolean again=false;
private ViewPager page;
private Bitmap bmImg1;
private Bitmap bmImg2;
private Bitmap bmImg3;
private String TAG;
ArrayList<Bitmap> IMAGES =new ArrayList<>();
ArrayList<String> DESCRIPTIONS =new ArrayList<>();
ArrayList<String> SHOTLEVEL=new ArrayList<>();
ArrayList<String> FILTERPHOTO=new ArrayList<>();
ArrayList<String> APERTUREPHOTO=new ArrayList<>();
ArrayList<String> SHUTTERPHOTO=new ArrayList<>();
ArrayList<String> ISOPHOTO=new ArrayList<>();
ArrayList<String> LENSPHOTO=new ArrayList<>();
String[] descriptionPhoto;
private String shot_levelPhoto;
private String shot_levelPhoto1;
private String shot_levelPhoto2;
private String filterPhoto;
private String filterPhoto1;
private String filterPhoto2;
private String aperturePhoto;
private String aperturePhoto1;
private String aperturePhoto2;
private String shutterPhoto;
private String shutterPhoto1;
private String shutterPhoto2;
private String isoPhoto;
private String isoPhoto1;
private String isoPhoto2;
private String focal_lengthPhoto;
private String focal_lengthPhoto1;
private String focal_lengthPhoto2;
private String[] shot_levelPhotoArray= new String[3];
private String[] filterPhotoArray= new String[3];
private String[] aperturePhotoArray=new String[3];
private String[] shutterPhotoArray=new String[3];
private String[] isoPhotoArray=new String[3];
private String[] focal_lengthPhotoArray=new String[3];
int numpics=1;
private int position_pic;
private String suggested_aperture;
private String suggested_filter;
private String suggested_iso;
private String suggested_shutter;
private String suggested_shot_level;
private String suggested_lens;
private LayoutInflater inflater;
private boolean firsttime;
private boolean secondtime;
private int oldposition=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
FileInputStream fis;
FileInputStream fis2;
FileInputStream fis3;
Bundle intent=getIntent().getExtras();
descriptionPhoto = intent.getStringArray("descriptionPhoto");
numpics = (int) intent.get("numpics");
position_pic = (int) intent.get("position_pic");
suggested_aperture= intent.getString("suggested_aperture");
suggested_filter= intent.getString("suggested_filter");
suggested_iso= intent.getString("suggested_iso");
suggested_shutter= intent.getString("suggested_shutter");
suggested_shot_level= intent.getString("suggested_shot_level");
suggested_lens= intent.getString("suggested_lens");
shot_levelPhoto=intent.getString("shot_levelPhoto");
shot_levelPhoto1=intent.getString("shot_levelPhoto1");
shot_levelPhoto2=intent.getString("shot_levelPhoto2");
shot_levelPhotoArray[0] = shot_levelPhoto;
if(!shot_levelPhoto1.equals("null")){
shot_levelPhotoArray[1]=shot_levelPhoto1;
if(!shot_levelPhoto2.equals("null")){
shot_levelPhotoArray[2]=shot_levelPhoto2;
}
}
filterPhoto =intent.getString("filterPhoto");
filterPhoto1 =intent.getString("filterPhoto1");
filterPhoto2 =intent.getString("filterPhoto2");
filterPhotoArray[0]= filterPhoto;
if(!filterPhoto1.equals("null")){
filterPhotoArray[1]=filterPhoto1;
if(!filterPhoto2.equals("null")){
filterPhotoArray[2]=filterPhoto2;
}
}
aperturePhoto =intent.getString("aperturePhoto");
aperturePhoto1 =intent.getString("aperturePhoto1");
aperturePhoto2 =intent.getString("aperturePhoto2");
aperturePhotoArray[0]= aperturePhoto;
if(!aperturePhoto1.equals("null")){
aperturePhotoArray[1]=aperturePhoto1;
if(!aperturePhoto2.equals("null")){
aperturePhotoArray[2]=aperturePhoto2;
}
}
shutterPhoto =intent.getString("shutterPhoto");
shutterPhoto1 =intent.getString("shutterPhoto1");
shutterPhoto2 =intent.getString("shutterPhoto2");
shutterPhotoArray[0]= shutterPhoto;
if(!shutterPhoto1.equals("null")){
shutterPhotoArray[1]=shutterPhoto1;
if(!shutterPhoto2.equals("null")){
shutterPhotoArray[2]=shutterPhoto2;
}
}
isoPhoto =intent.getString("isoPhoto");
isoPhoto1 =intent.getString("isoPhoto1");
isoPhoto2 =intent.getString("isoPhoto2");
isoPhotoArray[0]= isoPhoto;
if(!isoPhoto1.equals("null")){
isoPhotoArray[1]=isoPhoto1;
if(!isoPhoto2.equals("null")){
isoPhotoArray[2]=isoPhoto2;
}
}
focal_lengthPhoto=intent.getString("focal_lengthPhoto");
focal_lengthPhoto1=intent.getString("focal_lengthPhoto1");
focal_lengthPhoto2=intent.getString("focal_lengthPhoto2");
focal_lengthPhotoArray[0]= focal_lengthPhoto;
if(!focal_lengthPhoto1.equals("null")){
focal_lengthPhotoArray[1]=focal_lengthPhoto1;
if(!focal_lengthPhoto2.equals("null")){
focal_lengthPhotoArray[2]=focal_lengthPhoto2;
}
}
TextView txtaperture_suggested = (TextView) findViewById(R.id.aperture_suggested);
TextView txtfilter_suggested = (TextView) findViewById(R.id.filter_suggested);
TextView txtiso_suggested = (TextView) findViewById(R.id.iso_suggested);
TextView txtlens_suggested = (TextView) findViewById(R.id.lens_suggested);
TextView txtshutter_suggested = (TextView) findViewById(R.id.shutter_suggested);
TextView txtshot_levelsuggested = (TextView) findViewById(R.id.shot_levelsuggested);
if (suggested_shot_level == "1") {
txtshot_levelsuggested.setText("Easy");
} else if (suggested_shot_level =="2") {
txtshot_levelsuggested.setText("Medium");
} else if (suggested_shot_level =="3") {
txtshot_levelsuggested.setText("Difficult");
} else if (suggested_shot_level =="4"){
txtshot_levelsuggested.setText("Pro");
}
txtaperture_suggested.setText(suggested_aperture);
txtfilter_suggested.setText(suggested_filter);
txtiso_suggested.setText(suggested_iso);
txtshutter_suggested.setText(suggested_shutter);
txtlens_suggested.setText(suggested_lens);
/* TextView txtshutterPhoto = (TextView) findViewById(R.id.shutterPhoto);
TextView txtshutterPhoto2 = (TextView) findViewById(R.id.shutterPhoto2);
TextView txtshutterPhoto3 = (TextView) findViewById(R.id.shutterPhoto3);
TextView txtshot_levelPhoto = (TextView) findViewById(R.id.shot_levelPhoto);
TextView txtshot_levelPhoto2 = (TextView) findViewById(R.id.shot_levelPhoto2);
TextView txtshot_levelPhoto3 = (TextView) findViewById(R.id.shot_levelPhoto3);
TextView txtaperturePhoto = (TextView) findViewById(R.id.aperturePhoto);
TextView txtaperturePhoto2 = (TextView) findViewById(R.id.aperturePhoto2);
TextView txtaperturePhoto3 = (TextView) findViewById(R.id.aperturePhoto3);
TextView txtfilterPhoto = (TextView) findViewById(R.id.filterPhoto);
TextView txtfilterPhoto2 = (TextView) findViewById(R.id.filterPhoto2);
TextView txtfilterPhoto3 = (TextView) findViewById(R.id.filterPhoto3);
TextView txtisoPhoto = (TextView) findViewById(R.id.isoPhoto);
TextView txtisoPhoto2 = (TextView) findViewById(R.id.isoPhoto2);
TextView txtisoPhoto3 = (TextView) findViewById(R.id.isoPhoto3);
TextView txtfocal_lengthPhoto = (TextView) findViewById(R.id.lensPhoto);
TextView txtfocal_lengthPhoto2 = (TextView) findViewById(R.id.lensPhoto2);
TextView txtfocal_lengthPhoto3 = (TextView) findViewById(R.id.lensPhoto3);*/
/* if (shot_levelPhotoArray[0] == "1") {
txtshot_levelPhoto.setText("Easy");
shot_levelPhotoArray[0] = "Easy";
*//*txtshot_levelPhoto2.setText("Easy");
txtshot_levelPhoto3.setText("Easy");*//*
} else if (shot_levelPhotoArray[0] == "2") {
txtshot_levelPhoto.setText("Medium");
shot_levelPhotoArray[0] = "Medium";
*//* txtshot_levelPhoto2.setText("Medium");
txtshot_levelPhoto3.setText("Medium");*//*
} else if (shot_levelPhotoArray[0] == "3") {
txtshot_levelPhoto.setText("Difficult");
shot_levelPhotoArray[0] = "Difficult";
*//*txtshot_levelPhoto2.setText("Difficult");
txtshot_levelPhoto3.setText("Difficult");*//*
} else {
txtshot_levelPhoto.setText("Pro");
shot_levelPhotoArray[0] = "Pro";
*//* txtshot_levelPhoto2.setText("Pro");
txtshot_levelPhoto3.setText("Pro");*//*
}
txtshutterPhoto.setText(shutterPhoto);
txtisoPhoto.setText(isoPhoto);
txtfilterPhoto.setText(filterPhoto);
txtaperturePhoto.setText(aperturePhoto);
txtfocal_lengthPhoto.setText(focal_lengthPhoto);*/
/*txtshutterPhoto.setText(shutterPhoto[0]);
if (shutterPhoto.length > 1) {
txtshutterPhoto2.setText(shutterPhoto[1]);
if (shutterPhoto.length > 2) {
txtshutterPhoto3.setText(shutterPhoto[2]);
}
}
txtisoPhoto.setText(isoPhoto[0]);
if (isoPhoto.length > 1) {
txtisoPhoto2.setText(isoPhoto[1]);
if (isoPhoto.length > 2) {
txtisoPhoto3.setText(isoPhoto[2]);
}
}
txtfilterPhoto.setText(filterPhoto[0]);
if (filterPhoto.length > 1) {
txtfilterPhoto2.setText(filterPhoto[1]);
if ((filterPhoto.length > 2)) {
txtfilterPhoto3.setText(filterPhoto[2]);
}
}
txtaperturePhoto.setText(aperturePhoto[0]);
if (aperturePhoto.length > 1) {
txtaperturePhoto2.setText(aperturePhoto[1]);
if (aperturePhoto.length > 2) {
txtaperturePhoto3.setText(aperturePhoto[2]);
}
}*/
try {
fis = getApplicationContext().openFileInput("bmImg1");
bmImg1 = BitmapFactory.decodeStream(fis);
IMAGES.add(bmImg1);
DESCRIPTIONS.add(descriptionPhoto[0]);
SHOTLEVEL.add(shot_levelPhotoArray[0]);
FILTERPHOTO.add(filterPhotoArray[0]);
APERTUREPHOTO.add(aperturePhotoArray[0]);
SHUTTERPHOTO.add(shutterPhotoArray[0]);
ISOPHOTO.add(isoPhotoArray[0]);
LENSPHOTO.add(focal_lengthPhotoArray[0]);
fis.close();
if(numpics>1){
fis2 = getApplicationContext().openFileInput("bmImg2");
bmImg2 = BitmapFactory.decodeStream(fis2);
IMAGES.add(bmImg2);
DESCRIPTIONS.add(descriptionPhoto[1]);
SHOTLEVEL.add(shot_levelPhotoArray[1]);
FILTERPHOTO.add(filterPhotoArray[1]);
APERTUREPHOTO.add(aperturePhotoArray[1]);
SHUTTERPHOTO.add(shutterPhotoArray[1]);
ISOPHOTO.add(isoPhotoArray[1]);
LENSPHOTO.add(focal_lengthPhotoArray[1]);
fis2.close();
if(numpics>2){
fis3 = getApplicationContext().openFileInput("bmImg3");
bmImg3 = BitmapFactory.decodeStream(fis3);
IMAGES.add(bmImg3);
DESCRIPTIONS.add(descriptionPhoto[2]);
SHOTLEVEL.add(shot_levelPhotoArray[2]);
FILTERPHOTO.add(filterPhotoArray[2]);
APERTUREPHOTO.add(aperturePhotoArray[2]);
SHUTTERPHOTO.add(shutterPhotoArray[2]);
ISOPHOTO.add(isoPhotoArray[2]);
LENSPHOTO.add(focal_lengthPhotoArray[2]);
fis3.close();
}
}
}
catch (FileNotFoundException e) {
Log.d(TAG, "file not found");
e.printStackTrace();
}
catch (IOException e) {
Log.d(TAG, "io exception");
e.printStackTrace();
}
PagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), descriptionPhoto[position_pic]);
page = (ViewPager)findViewById(R.id.pager);
page.setAdapter(pagerAdapter);
page.setCurrentItem(position_pic);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void clear() {
IMAGES.clear();
DESCRIPTIONS.clear();
SHOTLEVEL.clear();
FILTERPHOTO.clear();
APERTUREPHOTO.clear();
SHUTTERPHOTO.clear();
ISOPHOTO.clear();
LENSPHOTO.clear();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return true;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
String description;
public ScreenSlidePagerAdapter(FragmentManager fm, String description) {
super(fm);
this.description=description;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
//this is called when notifyDataSetChanged() is called
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public boolean isViewFromObject(View view, Object object) {
if(object != null){
return ((Fragment)object).getView() == view;
}else{
return false;
}
}
/*#Override
public Fragment getItem(int position) {
ViewPagerFragment fragment = new ViewPagerFragment();
fragment.setAsset(IMAGES.get(position));
return fragment;
}*/
#Override
public Fragment getItem(int index) {
ViewPagerFragment fragment = new ViewPagerFragment();
//fragment.setAsset(IMAGES.get(index));
fragment.setAsset(IMAGES.get(index), DESCRIPTIONS.get(index));
ViewPagerFragment.newInstance(index,
SHOTLEVEL.get(index),
FILTERPHOTO.get(index),
APERTUREPHOTO.get(index),
SHUTTERPHOTO.get(index),
ISOPHOTO.get(index),
LENSPHOTO.get(index)); // Pages is an array of Strings
return fragment;
}
#Override
public int getCount() {
return IMAGES.size();
}
}
}
This is the Fragment
public class ViewPagerFragment extends Fragment {
private static final String BUNDLE_ASSET = "res";
private Bitmap asset;
String descriptionPhoto;
private TextView tv;
HashMap<Bitmap, String > map;
private static Bundle bundle;
public ViewPagerFragment() {
}
/*public int setAsset(Bitmap asset) {
this.asset = asset;
return 0;
}*/
public HashMap<Bitmap, String> setAsset(Bitmap asset, String description){
map= new HashMap<>();
this.asset = asset;
this.descriptionPhoto=description;
map.put(this.asset, this.descriptionPhoto);
return map;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view_pager_page, container, false);
if (savedInstanceState != null) {
if (asset == null && savedInstanceState.containsKey(BUNDLE_ASSET)) {
asset = savedInstanceState.getParcelable(BUNDLE_ASSET);
}
}
if (asset != null && descriptionPhoto!=null) {
TextView descriptionnote = (TextView) rootView.findViewById(R.id.note1);
if(descriptionPhoto.equals("null")){
descriptionPhoto="No description for this picture";
}
descriptionnote.setText(descriptionPhoto);
SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)rootView.findViewById(R.id.imageView);
imageView.setImage(ImageSource.bitmap(asset));
TextView txtshot_level = (TextView) rootView.findViewById(R.id.shot_levelPhoto);
TextView txtshutterPhoto = (TextView) rootView.findViewById(R.id.shutterPhoto);
TextView txtaperturePhoto = (TextView) rootView.findViewById(R.id.aperturePhoto);
TextView txtfilterPhoto = (TextView) rootView.findViewById(R.id.filterPhoto);
TextView txtisoPhoto = (TextView) rootView.findViewById(R.id.isoPhoto);
TextView txtfocal_lengthPhoto = (TextView) rootView.findViewById(R.id.lensPhoto);
txtshot_level.setText(bundle.getString("shot_levelcontent"));
txtshutterPhoto.setText(bundle.getString("shuttercontent"));
txtisoPhoto.setText(bundle.getString("isocontent"));
txtfilterPhoto.setText(bundle.getString("filtercontent"));
txtaperturePhoto.setText(bundle.getString("aperturecontent"));
txtfocal_lengthPhoto.setText(bundle.getString("lenscontent"));
}
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
View rootView = getView();
if (rootView != null) {
outState.putString(BUNDLE_ASSET, String.valueOf(asset));
}
}
public static Fragment newInstance(int position,
String shot_level,
String filter,
String aperture,
String shutter,
String iso,
String lens) {
ViewPagerFragment swipeFragment = new ViewPagerFragment();
bundle = new Bundle();
if (shot_level.equals("1")) {
bundle.putString("shot_levelcontent", "Easy");
} else if (shot_level.equals("2")) {
bundle.putString("shot_levelcontent", "Medium");
} else if (shot_level.equals("3")) {
bundle.putString("shot_levelcontent", "Difficult");
} else {
bundle.putString("shot_levelcontent", "Pro");
}
bundle.putString("filtercontent", filter);
bundle.putString("aperturecontent", aperture);
bundle.putString("shuttercontent", shutter);
bundle.putString("isocontent", iso);
bundle.putString("lenscontent", lens);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}

Layout issue, big vertical space between the viewtext elemens and divider in list item

below is a list_item layout. I don't understand why there is a big vertical space between the viewtext elemens and divider element inside a list item row ? What is wrong with this layout?
Screenshot here
My layout xml for list item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/companyName"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/table_text_selector"/>
<TextView
android:id="#+id/exchange"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_text_light_selector"
android:layout_below="#id/companyName"/>
<TextView
android:id="#+id/symbol"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_text_light_selector"
android:layout_below="#id/companyName"
android:layout_toLeftOf="#id/exchange"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:singleLine="true"
android:ellipsize="end"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/table_text_selector"
android:layout_alignParentRight="true"/>
<TextView
android:id="#+id/change"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_stock_change_text"
android:layout_alignParentRight="true"
android:layout_below="#id/price"/>
<TextView
android:id="#+id/percentChange"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_stock_change_text"
android:layout_alignBaseline="#id/change"
android:layout_alignBottom="#id/change"
android:layout_toLeftOf="#id/change"
android:layout_marginRight="5dp"/>
</RelativeLayout>
This is the fragment:
public class StockListFragment extends ItemListFragment<CurrentStock> {
#Inject BootstrapServiceProvider serviceProvider;
#Inject LogoutService logoutService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Injector.inject(this);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(R.string.no_stocks);
}
#Override
protected void configureList(Activity activity, ListView listView) {
super.configureList(activity, listView);
listView.setFastScrollEnabled(true);
listView.setDividerHeight(0);
getListAdapter().addHeader(activity.getLayoutInflater()
.inflate(R.layout.stock_list_item_labels, null));
}
#Override
LogoutService getLogoutService() {
return logoutService;
}
#Override
public Loader<List<CurrentStock>> onCreateLoader(int id, Bundle args) {
final List<CurrentStock> initialItems = items;
return new ThrowableLoader<List<CurrentStock>>(getActivity(), items) {
#Override
public List<CurrentStock> loadData() throws Exception {
try {
List<CurrentStock> latest = null;
if(getActivity() != null)
latest = serviceProvider.getService(getActivity()).getStocks();
if (latest != null)
return latest;
else
return Collections.emptyList();
} catch (OperationCanceledException e) {
Activity activity = getActivity();
if (activity != null)
activity.finish();
return initialItems;
}
}
};
}
public void onListItemClick(ListView l, View v, int position, long id) {
CurrentStock currentStock = ((CurrentStock) l.getItemAtPosition(position));
startActivity(new Intent(getActivity(), StockActivity.class).putExtra(STOCK, currentStock));
}
#Override
public void onLoadFinished(Loader<List<CurrentStock>> loader, List<CurrentStock> items) {
super.onLoadFinished(loader, items);
}
#Override
protected int getErrorMessage(Exception exception) {
return R.string.error_loading_stocks;
}
#Override
protected SingleTypeAdapter<CurrentStock> createAdapter(List<CurrentStock> items) {
return new StockListAdapter(getActivity().getLayoutInflater(), items);
}
}
This is the adapter
public class StockListAdapter extends SingleTypeAdapter<CurrentStock> {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMMM dd");
/**
* Create adapter
*
* #param inflater
* #param items
*/
public StockListAdapter(LayoutInflater inflater, List<CurrentStock> items) {
super(inflater, R.layout.stock_list_item);
setItems(items);
}
/**
* Create adapter
*
* #param inflater
*/
public StockListAdapter(LayoutInflater inflater) {
this(inflater, null);
}
#Override
public long getItemId(final int position) {
final String id = getItem(position).getSymbol();
return !TextUtils.isEmpty(id) ? id.hashCode() : super
.getItemId(position);
}
/**/
#Override
protected int[] getChildViewIds() {
return new int[] { R.id.companyName, R.id.exchange, R.id.symbol, R.id.price, R.id.change, R.id.percentChange };
}
#Override
protected void update(int position, CurrentStock currentStock) {
setText(0, currentStock.getCompanyName());
setText(1, currentStock.getExchange());
setText(2, currentStock.getSymbol());
setText(3, currentStock.getPrice().toString());
setText(4, currentStock.getChange().toString());
setText(5, currentStock.getPercentChange());
}
}
I don't have the listview it selvf. Btw. I need a divider except top and bottom divider ?
The problem lies in your code where you're using your divider code. By the way, why are you doing this? ... since ListView has its divider and dividerHeight?
Here's what I've came up with in a couple of minutes of coding using above layout (only removed the textColor attributes):
The code for above list:
public class MyListActivity extends FragmentActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.so_list_layout);
listView = (ListView) findViewById(R.id.localListView);
fillListView();
}
private void fillListView() {
final List<LDataRow> data = getRowData();
ArrayAdapter<LDataRow> adapter = new ArrayAdapter<MyListActivity.LDataRow>(this,
R.layout.so_list_row, data) {
private LDataRow getDataRow(int position) {
return data.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LDataRow row = getDataRow(position);
if (convertView == null) {
convertView = LayoutInflater.from(MyListActivity.this).inflate(
R.layout.so_list_row, parent, false);
}
TextView companyName = (TextView) convertView.findViewById(R.id.companyName);
companyName.setText(row.getCompanyName());
TextView exchange = (TextView) convertView.findViewById(R.id.exchange);
exchange.setText(row.getExchange());
TextView symbol = (TextView) convertView.findViewById(R.id.symbol);
symbol.setText(row.getSymbol());
TextView price = (TextView) convertView.findViewById(R.id.price);
price.setText(String.valueOf(row.getPrice()));
TextView change = (TextView) convertView.findViewById(R.id.change);
change.setText(String.valueOf(row.getChange()));
TextView percentChange = (TextView) convertView.findViewById(R.id.percentChange);
percentChange.setText(String.valueOf(row.getPercentChange()));
return convertView;
}
};
listView.setAdapter(adapter);
}
private List<LDataRow> getRowData() {
ArrayList<LDataRow> result = new ArrayList<MyListActivity.LDataRow>();
result.add(new LDataRow("Facebook", "Nasdaq", "E", 52.445, 0.0, 0));
result.add(new LDataRow("Advanced Micro", "NYSE", "D", 3.23, 0.0, 0));
result.add(new LDataRow("Genmas", "CPH", "G", -100, -3.0, -20.0));
return result;
}
private static class LDataRow {
private String companyName;
private String exchange;
private String symbol;
private double price;
private double change;
private double percentChange;
public LDataRow(String companyName, String exchange, String symbol, double price,
double change, double percentChange) {
this.companyName = companyName;
this.exchange = exchange;
this.symbol = symbol;
this.price = price;
this.change = change;
this.percentChange = percentChange;
}
public String getCompanyName() {
return companyName;
}
public String getExchange() {
return exchange;
}
public String getSymbol() {
return symbol;
}
public double getPrice() {
return price;
}
public double getChange() {
return change;
}
public double getPercentChange() {
return percentChange;
}
}
}
Use this in top RelativeLayout to have a bottom spacing:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="8dp" >
EDIT If you want to customize the divider, you can very well specify a custom drawable and a size. Here's what I've done with a simple layer-list, my_so_divider.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#ffffff" />
</shape>
</item>
<item>
<shape android:shape="line" >
<stroke
android:width="1dp"
android:color="#000000" />
</shape>
</item>
</layer-list>
Set it in the ListView:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/localListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ffff"
android:divider="#drawable/my_so_divider"
android:dividerHeight="24dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" >
</ListView>
Check the footerDividersEnabled, headerDividersEnabled, divider and dividerHeight attributes ... Feel free to play around with the drawable. The effect in below image:
// try this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/companyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#color/table_text_light_selector"
android:text="companyName"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="#+id/symbol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="symbol"/>
<TextView
android:id="#+id/exchange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exchange"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="right"
android:orientation="vertical">
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="end"
android:textColor="#color/table_text_light_selector"
android:text="price"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:id="#+id/percentChange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="percentChange"
android:layout_marginTop="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginRight="5dp"/>
<TextView
android:id="#+id/change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="change"
android:layout_marginTop="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Try the following code.. It will give you the similar result you are in need of:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center">
<TextView
android:id="#+id/companyName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:text="facebook"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:textColor="#color/table_text_selector"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="facebook"
android:layout_marginRight="5dp"
android:textColor="#color/table_text_selector"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/exchange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="facebook"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/percentChange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="22%"
android:textColor="#color/table_stock_change_text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginRight="5dp"/>
<TextView
android:id="#+id/change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.0"
android:layout_marginRight="5dp"
android:textColor="#color/table_stock_change_text"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>

Categories

Resources