I was stuck all day. Couldn't find my mistake.
I created a Custom ListView, and I just want to be able to click on it to launch a new intent in HourListView.
public class CustomList extends ArrayAdapter<String> {
private final ArrayList<String> hourList;
private final Activity context;
public CustomList(Activity context,
ArrayList<String> hourList) {
super(context, R.layout.hour_list_adapter, hourList);
this.context = context;
this.hourList = hourList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View rowView = view;
ViewHolder viewHolder = null;
// LayoutInflater inflater = context.getLayoutInflater();
// View rowView= inflater.inflate(R.layout.hour_list_adapter, parent, false);
if(rowView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.hour_list_adapter, parent, false);
viewHolder = new ViewHolder();
viewHolder.type_frequenceTV = (TextView) rowView.findViewById(R.id.type_frequence);
viewHolder.dateTV = (TextView) rowView.findViewById(R.id.date);
viewHolder.dureeTV = (TextView) rowView.findViewById(R.id.duree);
viewHolder.commentaireTV = (TextView) rowView.findViewById(R.id.commentaire);
viewHolder.simuIV = (ImageView) rowView.findViewById(R.id.simulateur);
viewHolder.doubleIV = (ImageView) rowView.findViewById(R.id.doubleFrequence);
rowView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)rowView.getTag();
}
viewHolder.type_frequenceTV.setText(HourListActivity.hourObjects.get(position).get("type_frequence").toString());
viewHolder.dureeTV.setText(HourListActivity.hourObjects.get(position).get("duree").toString());
viewHolder.commentaireTV.setText(HourListActivity.hourObjects.get(position).get("comment").toString());
Date dateAndTime = (Date) HourListActivity.hourObjects.get(position).get("date");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yy à HH:mm");
String formatted = format1.format(dateAndTime.getTime());
viewHolder.dateTV.setText("Le " + formatted);
if ((Boolean) HourListActivity.hourObjects.get(position).get("double"))
{
viewHolder.doubleIV.setVisibility(View.VISIBLE);
}
else
{
viewHolder.doubleIV.setVisibility(View.GONE);
}
if ((Boolean) HourListActivity.hourObjects.get(position).get("simulateur"))
{
viewHolder.simuIV.setVisibility(View.VISIBLE);
}
else
{
viewHolder.simuIV.setVisibility(View.GONE);
}
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return rowView;
}
static class ViewHolder
{
TextView type_frequenceTV;
TextView dateTV ;
TextView dureeTV ;
TextView commentaireTV ;
ImageView simuIV ;
ImageView doubleIV ;
}
}
Then this is the HourListActivity where I want to be able to click.
public class HourListActivity extends AppCompatActivity {
//ArrayAdapter<String> arrayAdapter;
CustomList adapter;
ListView hourListView;
static ArrayList<String> hourList;
static ArrayList<String> hourListID;
static ArrayList<ParseObject> hourObjects = new ArrayList<ParseObject>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hour_list);
hourList = new ArrayList<>();
hourListID = new ArrayList<>();
hourListView = (ListView) findViewById(R.id.listView);
adapter = new CustomList(HourListActivity.this,hourList);
//arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hourList);
hourListView.setAdapter(adapter);
hourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("CLIC !!!!!!!!!!!!!!!!!!!!!");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Frequence");
query.getInBackground(hourListID.get(position), new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), ModifyHourActivity.class);
intent.putExtra("objectID", object.getObjectId());
startActivity(intent);
} else {
// something went wrong
}
}
});
}
});
ParseQuery<ParseObject> query = ParseQuery.getQuery("Frequence");
query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
System.out.println("username: " + ParseUser.getCurrentUser().getUsername() );
query.orderByDescending("date");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null)
{
if (objects.size() > 0)
{
hourObjects.clear();
for (ParseObject frequence : objects)
{
String result = "";
result += frequence.get("date") + " - "
+ frequence.get("type_frequence") + " - "
+ frequence.get("duree") + " - "
+ frequence.get("comment") + " - "
+ frequence.get("double") + " - "
+ frequence.get("simulateur") + " - ";
System.out.println("Résultat : " + result);
hourList.add(result.toString());
hourListID.add(frequence.getObjectId());
ParseObject newHour = new ParseObject("Temp");
newHour.put("username", frequence.get("username"));
// newHour.put("id", frequence.get("objectId"));
newHour.put("type_frequence", frequence.get("type_frequence"));
newHour.put("date", frequence.get("date"));
newHour.put("duree", frequence.get("duree"));
newHour.put("comment", frequence.get("comment"));
newHour.put("double", frequence.get("double"));
newHour.put("simulateur", frequence.get("simulateur"));
hourObjects.add(newHour);
}
Toast.makeText(HourListActivity.this, "Liste des heures récupérée !",
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
else
{
}
}
});
A lastly my xml file for the Custom View:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:layout_margin="5dp"
>
<TextView
android:id="#+id/type_frequence"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:gravity="center"
android:text="DEP S"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/buttonTextColor"
android:paddingLeft="10dp"
android:paddingRight="10dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:textSize="15dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="12 avril 2016 - 08:00"
android:layout_marginLeft="5dp"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<TextView
android:id="#+id/duree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="1.00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/buttonTextColor"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp"
android:paddingRight="10dp"
/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:orientation="horizontal">
<TextView
android:id="#+id/commentaire"
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:text="Commentaire"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true">
<ImageView
android:id="#+id/doubleFrequence"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_column="1"
android:src="#drawable/double_96" />
<ImageView
android:id="#+id/simulateur"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_column="1"
android:src="#drawable/simu_96"
android:layout_toStartOf="#+id/doubleFrequence" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Thanks in advance for any help ! :)
What happens when you delete this part in your adapter ?
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
I guess what happens is that the view are created after you have defined the ItemClickListener in your activity, resulting in the ClickListener being overriden at run time by the one in your adapter.
As far as I am concerned if you are facing an error with setOnClickListener you can try this
Go to Tools--> sync with Gradle.
It helped me when I was stucked with the intent problem!
Related
Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.
Parent Recyclerview Adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String itemTitle = dataList.get(i).getTitle();
final String itemDescription = dataList.get(i).getDescription();
ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();
itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle, expandImage;
protected ImageView bookmarkImage,largeImage;
protected RecyclerView recyclerSmallImageList;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.title);
this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
this.largeImage = (ImageView) view.findViewById(R.id.large_image);
this.expandImage = (TextView) view.findViewById(R.id.expand);
this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);
}
}
}
Nested Recyclerview Adapter:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SmallImages> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SmallImages singleItem = itemsList.get(i);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
//this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.
/////Adapter class
public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {
private Context mContext;
private int rowLayout;
private List<ModelRouteDetailsUp> dataMembers;
private ArrayList<ModelRouteDetailsUp> arraylist;
private ArrayList<ModelKidDetailsUp> arraylist_kids;
List<String> wordList = new ArrayList<>();
Random rnd = new Random();
int randomNumberFromArray;
private ModelRouteDetailsUp personaldata;
private ProgressDialog pDialog;
private ConnectionDetector cd;
String img_baseurl = "";
String item = "";
public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
this.mContext = mcontext;
this.rowLayout = rowLayout;
this.dataMembers = tripList;
wordList.clear();
this.img_baseurl = img_baseurl;
arraylist = new ArrayList<>();
arraylist_kids = new ArrayList<>();
arraylist.addAll(dataMembers);
cd = new ConnectionDetector(mcontext);
pDialog = KPUtils.initializeProgressDialog(mcontext);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new AdapterTodayTrip.VHItem(v);
}
#Override
public int getItemCount() {
return dataMembers.size();
}
#Override
public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
try {
personaldata = dataMembers.get(position);
if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
}
****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
if (personaldata.getKidlist().size() > 0) {
viewHolder.linear_childview.setVisibility(View.VISIBLE);
viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
viewHolder.id_gallery.removeAllViews();
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(0, 0, 8, 0);
LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < personaldata.getKidlist().size(); i++) {
View view = layoutInflater.inflate(R.layout.view_child_list, null);
view.setLayoutParams(buttonLayoutParams);
RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);
TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
int count = i + 1;
String count1 = "0";
if (count <= 10) {
count1 = "0" + count;
}
tv_count.setText(String.valueOf(count1));
viewHolder.id_gallery.addView(view);
final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
if(!baseurl.isEmpty()) {
iv_circular.setTag(baseurl);
}
if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
bgShape.setColor(Color.parseColor("#A6b1a7a6"));
rl_txt.setVisibility(View.GONE);
//rl_img.setVisibility(View.VISIBLE);
tv_name.setVisibility(View.GONE);
Log.d("aimg_baseurl", baseurl);
try {
Picasso.with(mContext)
.load(baseurl)
.resize(60,60)
.centerCrop()
.into(iv_circular);
iv_circular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url=iv_circular.getTag().toString().trim();
if(!url.isEmpty())
KPUtils.showToastShort(mContext,url);
Picasso.with(mContext)
.load(url)
.resize(60,60)
.centerCrop()
.into(viewHolder.img_child);
}
});
} catch (Exception e) {
}
} else {
}
}
}else{
viewHolder.linear_childview.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class VHItem extends RecyclerView.ViewHolder {
CardView cv_members;
ImageView img_child;
TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
LinearLayout id_gallery,linear_childview;
public VHItem(View itemView) {
super(itemView);
img_child= (ImageView) itemView.findViewById(R.id.img_child);
cv_members = (CardView) itemView.findViewById(R.id.cv_members);
tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
}
}
}
/////////////////////////// this layout is inflated in every row
view_child_list
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/iv_circular"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#d27959"
app:civ_border_width="1dp" />
<RelativeLayout
android:id="#+id/rl_txt"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="gone">
<com.app.kidpooldriver.helper.CircularTextView
android:id="#+id/tv_name"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="70dp"
android:layout_height="70dp"
android:gravity="center"
android:text="01"
android:textColor="#color/white"
android:textSize="35sp"
tools:ignore="MissingPrefix" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="visible">
<TextView
android:id="#+id/tv_count"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="01"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#ffffff"
android:textStyle="bold"
tools:ignore="MissingPrefix" />
</RelativeLayout>
</FrameLayout>
///// this is the mianlayout which is inflated.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin"
android:elevation="#dimen/elevation"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/main_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:layout_marginTop="#dimen/fifteen"
android:orientation="horizontal"
android:paddingLeft="#dimen/ten">
<TextView
android:id="#+id/tv_trip_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#KD09201701"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/twenty"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_trip_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/light_green"
android:gravity="center"
android:padding="5dp"
android:text="In Progress"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
</LinearLayout>
<TextView
android:id="#+id/tv_vehicle_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:text="Route 26U-26D"
android:visibility="gone"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/route_textcolor" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_trip_start_time"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="06:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor" />
<TextView
android:id="#+id/tv_trip_end_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="08:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/tv_trip_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:visibility="gone"
android:paddingRight="20dp"
android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/grey_textcolor"
android:textStyle="normal" />
<ImageView
android:id="#+id/img_child"
android:layout_width="200dp"
android:layout_gravity="center"
android:layout_height="200dp" />
<LinearLayout
android:id="#+id/linear_childview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fifteen"
android:orientation="horizontal">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:scrollbars="none">
<LinearLayout
android:id="#+id/id_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
<LinearLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/ly_ring_circular"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_total_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:ignore="MissingPrefix"
fontPath="fonts/Poppins-Bold.ttf"
android:text="+20"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
/////POJO CLASS &json parsing & Adapter /////
public class ModelRouteDetailsUp {
String city_id;
String area_name;
String area_status;
String is_active;
String areas;
private ArrayList<ModelKidDetailsUp> kidlist;
///////this is the kid list
public ArrayList<ModelKidDetailsUp> getKidlist() {
return kidlist;
}
public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
this.kidlist = kidlist;
}
}
**///json parsing.......**
public boolean addRideDetails(JSONObject jsonObject) {
Boolean flag = false;
String isstatus = "";
if (jsonObject != null && jsonObject.length() > 0) {
try {
JSONArray mainArray = jsonObject.getJSONArray("schedules");
for (int i = 0; i < mainArray.length(); i++) {
ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
JSONObject c = mainArray.getJSONObject(i);
////// For Route Details //////
JSONObject route_details = c.getJSONObject("route_details");
modelRouteDetails.setDs_id(route_details.optString("ds_id"));
modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
modelRouteDetails.setRoute_id(route_details.optString("route_id"));
modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
modelRouteDetails.setStart_time(route_details.optString("start_time"));
modelRouteDetails.setEnd_time(route_details.optString("end_time"));
////// For Allotted Kids //////
JSONArray kidArray = c.getJSONArray("alloted_kids");
ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
if (kidArray.length() > 0) {
for (int j = 0; j < kidArray.length(); j++) {
ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
JSONObject kidObject = kidArray.getJSONObject(j);
kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
genre.add(kidDetailsUp);
}
}
///////add the kidlist here
modelRouteDetails.setKidlist(genre);
////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
**/////adapter callfrom class**
private void showData() {
if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
rv_trip_list.setAdapter(adapterTodayTrip);
}else {
tv_msg.setVisibility(View.VISIBLE);
}
}
Generally, the solution is to pass custom interface listener into the nested adapter and than the nested adapter will report any time one of his item clicked.
1.
You can create interface like:
public interface INestedClicked {
onNestedItemClicked(Drawable drawble)
}
2.
Pass in the constructor of SectionListDataAdapter a INestedClicked:
SectionListDataAdapter itemListDataAdapter = newSectionListDataAdapter(mContext, singleSectionItems, new INestedClicked() {
#Override
void onNestedItemClicked(Drawable drawble) {
// Do whatever you need after the click, you get the drawable here
}
});
In the constructor of SectionListDataAdapter save the instance of the listener as adapter parameter
private INestedClicked listener;
4.
When nested item clicked report the listener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onNestedItemClicked(imageView.getDrawable());
}
}
I working on one Shopping Cart application.
In which i show list of products and in that every raw there is "Add to Cart" button,
Whenever user clicks on it then that button goes to disable and another view which holds add and subtract quantity should be display.
But when i clicks on any single product "Add to Cart" button then that view is going to be update, But when i scroll listview then another view gets update automatically (Not all).
Adapter
public class CategoryProductListAdapter extends BaseAdapter {
Context context;
ArrayList<ProductDetailsModel> productDetailsModels;
FragmentManager fragmentManager;
LayoutInflater inflater;
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels) {
this.context = context;
this.productDetailsModels = productDetailsModels;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels,FragmentManager fragmentManager) {
this.context = context;
this.productDetailsModels = productDetailsModels;
this.fragmentManager = fragmentManager;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return productDetailsModels.size();
}
#Override
public Object getItem(int i) {
return productDetailsModels.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public class Holder {
LinearLayout llProductRawMain, llProductQty;
ImageView imgProduct;
TextView txtProductTitle, txtProductUnit;
Spinner spProductUnits;
Button btnAddProduct, btnSubProduct;
EditText etNoOfProduct;
TextView txtProductPrice;
Button btnAddToCart;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final Holder holder;
if (view == null) {
holder = new Holder();
view = inflater.inflate(R.layout.category_product_list_raw, viewGroup, false);
holder.llProductRawMain = (LinearLayout) view.findViewById(R.id.llProductRawMain);
holder.llProductQty = (LinearLayout) view.findViewById(R.id.llProductQty);
holder.imgProduct = (ImageView) view.findViewById(R.id.imgProduct);
holder.txtProductTitle = (TextView) view.findViewById(R.id.txtProductTitle);
holder.txtProductUnit = (TextView) view.findViewById(R.id.txtProductUnit);
holder.spProductUnits = (Spinner) view.findViewById(R.id.spProductUnits);
holder.btnAddProduct = (Button) view.findViewById(R.id.btnAddProduct);
holder.btnSubProduct = (Button) view.findViewById(R.id.btnSubProduct);
holder.etNoOfProduct = (EditText) view.findViewById(R.id.etNoOfProduct);
holder.txtProductPrice = (TextView) view.findViewById(R.id.txtProductPrice);
holder.btnAddToCart = (Button) view.findViewById(R.id.btnAddToCart);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.txtProductTitle.setText(Html.fromHtml(productDetailsModels.get(i).getName()));
if (productDetailsModels.get(i).getUnits().size() > 0) {
holder.txtProductUnit.setVisibility(View.GONE);
holder.spProductUnits.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(0).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(0).getPrice());
ArrayList<ProductUnitModel> units = new ArrayList<>();
units.clear();
units.addAll(productDetailsModels.get(i).getUnits());
ProductUnitsListAdapter productUnitsListAdapter = new ProductUnitsListAdapter(context, units);
holder.spProductUnits.setAdapter(productUnitsListAdapter);
holder.spProductUnits.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int j, long l) {
holder.etNoOfProduct.setText("1");
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(j).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(j).getPrice());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
holder.spProductUnits.setVisibility(View.GONE);
holder.txtProductUnit.setVisibility(View.VISIBLE);
holder.txtProductUnit.setText(productDetailsModels.get(i).getUnit());
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getImage(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getPrice());
}
holder.llProductRawMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (productDetailsModels.get(i).getUnits().size() > 0) {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", true);
intent.putExtra("productUnitPos", holder.spProductUnits.getSelectedItemPosition());
context.startActivity(intent);*/
//FragmentManager fragmentManager = fra;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = true;
int productUnitPos = holder.spProductUnits.getSelectedItemPosition();
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
} else {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", false);
intent.putExtra("productUnitPos", 0);
context.startActivity(intent);*/
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = false;
int productUnitPos = 0;
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
}
}
});
holder.btnAddProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty++;
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
}
});
holder.btnSubProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty--;
if (qty > 0) {
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
} else {
Toast.makeText(context, "Quntity can not be zero!", Toast.LENGTH_SHORT).show();
}
}
});
holder.btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final boolean isUserLogin = AppMethod.getBooleanPreference((Activity) context, AppConstant.PREF_IS_LOGGED_IN);
if (isUserLogin) {
holder.llProductQty.setVisibility(View.VISIBLE);
holder.btnAddToCart.setVisibility(View.GONE);
String product_id;
String variation_id;
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, 1);
} else {
Toast.makeText(context, "Please Login for Add to Cart !", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void updateCart(String product_id, String variation_id, int qty) {
String customer_id = AppMethod.getStringPreference((Activity) context, AppConstant.PREF_USER_ID);
if (AppMethod.isNetworkConnected((Activity) context)) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product_id", product_id);
jsonObject.put("variation_id", variation_id);
jsonObject.put("qty", qty);
jsonObject.put("customer_id", customer_id);
WsHttpPostJson wsHttpPostJson = new WsHttpPostJson(context, AppConstant.ADD_CART_WS, jsonObject.toString());
wsHttpPostJson.execute(AppConstant.ADD_CART_WS_URL);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
}
XML of Adapter
<?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:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductRawMain"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:background="#drawable/product_grid_item_bg"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgProduct"
android:layout_width="match_parent"
android:layout_height="#dimen/_80sdp"
android:padding="#dimen/_5sdp"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:padding="#dimen/view_margin">
<TextView
android:id="#+id/txtProductTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:minLines="2"
android:textSize="#dimen/_11sdp"
android:text="Product Title"
android:textColor="#000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtProductUnit"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center_vertical"
android:padding="5dp"
android:textSize="#dimen/_11sdp"
android:text="Product Unit" />
<Spinner
android:id="#+id/spProductUnits"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center"
android:background="#drawable/icon_dropdown"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/txtProductPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="\u20B9 200"
android:textStyle="bold"
android:textSize="#dimen/_13sdp"
android:textColor="#185401" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductQty"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/app_color"
android:orientation="horizontal"
android:visibility="gone">
<Button
android:id="#+id/btnSubProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_minus"
android:gravity="center" />
<EditText
android:id="#+id/etNoOfProduct"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:background="#null"
android:ems="10"
android:enabled="false"
android:textSize="#dimen/_10sdp"
android:gravity="center"
android:inputType="number"
android:text="1"
android:textColor="#color/white" />
<Button
android:id="#+id/btnAddProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_plus"
android:gravity="center" />
</LinearLayout>
<Button
android:id="#+id/btnAddToCart"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/add_to_cart_btn_bg"
android:text="ADD TO CART"
android:textSize="#dimen/_12sdp"
android:textColor="#color/app_color" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I suffer from this also and realize that i think this links are help you.
Answer-1
Answer-2
Thanks
I'm trying to put a image and some textview on my list fragment, the thing it's that I can but when I execute the program I can't select any item, could somebody tellme how can I fix that, I'll paste you my code:
xml with the image and the textviews:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imagen"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:src="#mipmap/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/nombreUsuario"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imagen" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/calle"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/fechaPedido"
android:layout_alignBottom="#+id/imagen"
android:layout_toEndOf="#+id/imagen" />
arrayadapter class:
public class AdaptadorDatosListviewChofer extends ArrayAdapter<ParseObject>{
private Context mContexto;
private List<ParseObject> mPedido;
public AdaptadorDatosListviewChofer(Context contexto, List<ParseObject> pedido) {
super(contexto, R.layout.item_lista_chofer,pedido);
mContexto=contexto;
mPedido=pedido;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContexto).inflate(R.layout.item_lista_chofer,null);
holder = new ViewHolder();
holder.imagen = (ImageView) convertView.findViewById(R.id.imagen);
holder.nombre = (TextView) convertView.findViewById(R.id.nombreUsuario);
holder.domicilio= (TextView) convertView.findViewById(R.id.calle);
holder.fechaPedido=(TextView) convertView.findViewById(R.id.fechaPedido);
holder.imagen.setImageResource(R.mipmap.ic_launcher);
holder.nombre.setText("prueba");
}
return convertView;
}
private static class ViewHolder{
ImageView imagen;
TextView nombre;
TextView domicilio;
TextView fechaPedido;
}
}
fragment where i have the list:
public class FragmentoPrincipalChofer extends ListFragment {
private List<ParseObject> mPedido;
private List<ParseObject> mViaje;
private ListView mLista;
private Runnable r;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.fragmento_principal_chofer, container, false);
mLista = (ListView)x.findViewById(android.R.id.list);
return x;
}
#Override
public void onResume() {
super.onResume();
// logica de recibir pedidos
final Handler handler = new Handler();
r = new Runnable() {
public void run() {
handler.postDelayed(r, 10000);
//obtener pedido de taxi
ParseQuery<ParseObject> query = ParseQuery.getQuery("Pedido");
query.whereEqualTo("chofer", "chofer1");
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> pedido, com.parse.ParseException e) {
if (e == null) {
mPedido = pedido;
String[] nombreUsuarios = new String[mPedido.size()];
int i = 0;
for (ParseObject pedidos : mPedido) {
nombreUsuarios[i] = pedidos.getString("cliente");
i++;
}
AdaptadorDatosListviewChofer adaptador = new AdaptadorDatosListviewChofer(getListView().getContext(),mPedido);
setListAdapter(adaptador);
} else {
}
}
});
}
};
r.run();
ClickPedido();
}
public void ClickPedido(){
mLista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//verificar si aun existe el pedido en la base de datos
final String clienteSeleccionado = (String) mLista.getItemAtPosition(position);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Pedido");
query.whereEqualTo("usuario",clienteSeleccionado );
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> pedido, com.parse.ParseException e) {
if (e == null) {
//guardar viaje tomado por chofer
ParseObject Viaje = new ParseObject("Viaje");
Viaje.put("chofer", "chofer1");
Viaje.put("cliente", clienteSeleccionado);
Viaje.saveInBackground();
//borrar pedido xque paso a viaje
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Pedido");
query.whereEqualTo("cliente", clienteSeleccionado);
query.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject pedido, ParseException e) {
try {
pedido.delete();
pedido.saveInBackground();
} catch (ParseException ex) {
ex.printStackTrace();
}
}
});
} else {
//debo cambiarlo por un dialog
Toast.makeText(getContext(),"el pedido ya fue tomado",Toast.LENGTH_LONG).show();
}
}
});
}
});
}
}
xml of that fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ListView
android:layout_width="match_parent"
android:layout_height="420dp"
android:id="#android:id/list"
android:layout_weight="0.82"
android:layout_marginTop="60dp" />
</LinearLayout>
the problem is caused by your ImageButton try to add to your XML file this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:descendantFocusability="blocksDescendants" > //Defines the relationship between the ViewGroup and its descendants
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imagen"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:src="#mipmap/ic_launcher"
android:focusable="false" // set the focusability to false
android:focusableInTouchMode="false" // also here /> ...
I have grid view , on which each item consists of few images and text . When it loads for the first time , everything is fine but if I scroll to the bottom and the go back to top some two images are gone from a item , and it goes randomly .
here is the code for Grid view
<GridView
android:id="#+id/testR_grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:columnWidth="#dimen/gridview_column_width"
android:horizontalSpacing="#dimen/grid_horizontal_spacing"
android:listSelector="#drawable/gridview_background"
android:numColumns="auto_fit"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:verticalScrollbarPosition="right"
android:verticalSpacing="#dimen/grid_vertical_spacing"
android:fastScrollEnabled="false"/>
Here the code for single item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginTop="5dp"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/blurry_shadow_rect">
<com.joooonho.SelectableRoundedImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/item_image"
android:layout_width="match_parent"
android:layout_height="#dimen/gridview_column_width"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="-5dp"
app:sriv_left_bottom_corner_radius="0dip"
app:sriv_left_top_corner_radius="4dip"
app:sriv_right_bottom_corner_radius="0dip"
app:sriv_right_top_corner_radius="4dip" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/item_image"
android:layout_marginBottom="5dp"
android:layout_marginLeft="2dp"
android:orientation="horizontal"
android:weightSum="100">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="35">
<TextView
android:id="#+id/item_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_gravity="start"
android:layout_marginBottom="5dp"
android:ellipsize="end"
android:fontFamily="sans-serif-light"
android:maxLines="1"
android:text=""
android:textColor="#color/bodyText"
android:textSize="#dimen/GridHeader" />
<TextView
android:id="#+id/item_TestA_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/item_text"
android:layout_marginBottom="10dp"
android:alpha=".5"
android:ellipsize="end"
android:maxLines="1"
android:text=""
android:textColor="#color/bodyText"
android:textSize="#dimen/GridHeader2" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="65">
<TextView
android:id="#+id/item_testR_free_text"
style="#style/textview_grid_free_banner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:fontFamily="sans-serif-light"
android:maxLines="1"
android:padding="2dp"
android:singleLine="true"
android:text=" FREE " />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:id="#+id/already_owned"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:singleLine="true"
android:layout_marginLeft="20dp"
android:layout_marginBottom="5dp"
android:visibility="gone"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:src="#drawable/ic_testR_bought_36dp" />
<ImageButton
android:id="#+id/item_testR_more_options"
android:layout_width="#dimen/image_button_more"
android:layout_height="#dimen/image_button_more"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/item_testR_free_text"
android:alpha=".5"
android:background="#drawable/imagebutton_background"
android:clickable="true"
android:focusable="false"
android:src="#drawable/ic_more_vert_black_24dp" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
The elements are randomly missing are text view which id is item_testR_free_text and imageview which id is already_owned . One thing also to be noted the visibility of these two items are conditional .
Here is my code for adapter
public class TestRGridViewAdapter extends ArrayAdapter<TestR> {
Context context;
int layoutResourceId;
List<TestR> data = new ArrayList<TestR>();
RecordHolder holder = null;
//DiskCache imgCache;
TestA TestA;
TestR item;
FragmentActivity mFragmentActivity;
boolean is_local = false;
List<Track> trackList;
public TestR getItem() {
return item;
}
public void setItem(TestR item) {
this.item = item;
}
public TestRGridViewAdapter(Context context, int layoutResourceId,
List<TestR> data, FragmentActivity mFragmentActivity, boolean is_local) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.mFragmentActivity = mFragmentActivity;
// imgCache = Parameters.imgCache;
this.is_local = is_local;
}
public TestRGridViewAdapter(Context context, int layoutResourceId,
List<TestR> data, FragmentActivity mFragmentActivity) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.mFragmentActivity = mFragmentActivity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
//LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = LayoutInflater.from(context).inflate(layoutResourceId, null);
//row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.item_testR_free_text = (TextView) row.findViewById(R.id.item_testR_free_text);
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.txtTestAName = (TextView) row.findViewById(R.id.item_TestA_name);
holder.imageItem = (SelectableRoundedImageView) row.findViewById(R.id.item_image);
holder.item_testR_more_options = (ImageButton) row.findViewById(R.id.item_testR_more_options);
holder.already_owned = (ImageView) row.findViewById(R.id.already_owned);
// holder.grid_swipe_refresh_layout = (SwipeRefreshLayout) row.findViewById(R.id.grid_swipe_refresh_layout);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
item = data.get(position);
holder.txtTitle.setText(item.getName());
// else
// holder.txtArtitName.setText("");
//holder.imageItem.setImageBitmap(item.getImage());
try {
if (item.getTestA_id() == null)
item = new SaveData(context).get_online_testR(item.getTestR_id());
TestA = Helper.getDaoSession(context).getTestADao().load(item.getTestA_id());
if (TestA == null) {
TestA = new SaveData(context).get_save_TestA(item.getTestA_id());
}
// if (TestA != null)
holder.txtTestAName.setText((TestA != null) ? TestA.getName() : "");
// else
// TestA = new SaveData(context).get_save_TestA(item.getTestA_id());
if (!is_local) {
if(!DBQuery.is_owner(context,item.getTestR_id())) {
Log.d("test","not owner - "+item.getName());
holder.item_testR_free_text.setText(
UXHelper.getPriceFromString(Parameters.price_type.equals("local_price") ?
item.getLocal_price().toString() : item.getPrice().toString()));
holder.already_owned.setVisibility(View.INVISIBLE);
holder.item_testR_more_options.setOnClickListener(new testR_popup_onClick(context, item, holder.item_testR_more_options, mFragmentActivity, TestA));
}else {
Log.d("test","owner - "+item.getName());
holder.item_testR_free_text.setVisibility(View.INVISIBLE);
holder.already_owned.setVisibility(View.VISIBLE);
holder.item_testR_more_options.setOnClickListener(new testR_popup_onClick(context, item, holder.item_testR_more_options, mFragmentActivity, TestA));
}
} else {
Log.d("test","local - "+item.getName());
holder.already_owned.setVisibility(View.INVISIBLE);
boolean synced = true;
trackList = new ArrayList<Track>();
List<Track> trackListTmp = new SaveData(context).get_tracks_local(item.getTestR_id());
boolean testR_owner = DBQuery.is_owner(context, trackListTmp.get(0).getTestR_id());
for (Track t : trackListTmp) {
boolean track_owner = DBQuery.is_owner(context, t.getTrack_id(), t.getTestR_id());
if (track_owner)
trackList.add(t);
if (testR_owner || track_owner) {
if (t.getSynced_dir() == null) {
synced = false;
// break;
} else if (!new File(t.getSynced_dir()).exists()) {
synced = false;
// break;
}
}
}
if (synced) {
Log.d("test","synched - "+item.getName());
holder.item_testR_free_text.setVisibility(View.VISIBLE);
holder.item_testR_free_text.setText("Synced");
} else {
Log.d("test","not synched - "+item.getName());
holder.item_testR_free_text.setVisibility(View.INVISIBLE);
holder.item_testR_more_options.setOnClickListener(
new testR_popup_downloaded_onCLick(context, item, holder.item_testR_more_options, mFragmentActivity, TestA,
trackList.toArray(new Track[trackList.size()]), synced));
}
}
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
holder.imageItem.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
holder.imageItem.setImageResource(R.drawable.ic_example_36);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
holder.imageItem.setImageResource(R.drawable.ic_example_36);
}
};
if (Parameters.mPicasso == null)
Parameters.mPicasso = new Picasso.Builder(context)
.build();
Parameters.mPicasso.load("http://" + context.getString(R.string.ip) + "/" +
context.getString(R.string.TestRsController) + "/" + context.getString(R.string.TESTR_THUMB_URL)
+ "/" + item.getTestR_id()+"/"+Parameters.dpi)
.placeholder(R.drawable.ic_example_36)
.error(R.drawable.ic_example_36)
.into(holder.imageItem);
} catch (Exception ex) {
new Logger(context).appendLog("Error in TestR grid view item " + ex.getMessage());
}
return row;
}
static class RecordHolder {
// SwipeRefreshLayout grid_swipe_refresh_layout;
TextView txtTitle;
TextView txtTestAName;
SelectableRoundedImageView imageItem;
TextView item_testR_free_text;
ImageButton item_testR_more_options;
ImageView already_owned;
}
}
based on an example i tried to create a ListView that displays custom ListItems. I define the ListItem in XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/icon" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:singleLine="true"
android:text="Example application"
android:textSize="16sp" />
</RelativeLayout>
I created a class to hold the data shown in a ListItem:
public class UserRecord {
public String username;
public String email;
public UserRecord(String username, String email) {
this.username = username;
this.email = email;
}
}
I also have a custom ArrayAdapter:
public class UserItemAdapter extends ArrayAdapter<UserRecord> {
private ArrayList<UserRecord> users;
public LayoutInflater vi;
private Context context;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<UserRecord> users) {
super(context, textViewResourceId, users);
this.users = users;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
UserRecord user = users.get(position);
if (user != null) {
TextView username = (TextView) v.findViewById(R.id.firstLine);
TextView email = (TextView) v.findViewById(R.id.secondLine);
Log.v(TAG, "user " + user.username);
Log.v(TAG, "mail " + user.email);
if (username != null) {
Log.v(TAG, "username NOT null");
username.setText("user " + user.username);
}
if (email != null) {
Log.v(TAG, "email NOT null");
email.setText("Email: " + user.email);
}
}
return v;
}
}
Initialisation:
ArrayList<UserRecord> appointment;
UserItemAdapter aa;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
appointment = new ArrayList<UserRecord>();
aa = new UserItemAdapter(this, android.R.layout.simple_list_item_1, appointment);
lv.setAdapter(aa);
}
And finally, when i push a button:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
aa.add(ur);
} else {
Log.v(TAG, "unknown");
}
}
Problem is that "email" is displayed, but "username" not, though it is handled the same way, i see no difference. Also, the if() where it should be set is taken.
Has anybody got a hint on what is wrong?
Best regards
Torsten
Change this
aa = new UserItemAdapter(this, android.R.layout.simple_list_item_1, appointment);
To this;
aa = new UserItemAdapter(this, R.layout.listitem, appointment);
And try this:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
appointment.add(ur);
aa.notifyDataSetChanged();
} else {
Log.v(TAG, "unknown");
}
}
I could be mistaken, but I am almost sure you should be doing this:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
users.add(ur);
} else {
Log.v(TAG, "unknown");
}
}
Instead of:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
aa.add(ur);
} else {
Log.v(TAG, "unknown");
}
}
I have never added an item to my ADAPTER class, but always to the LIST of objects. In this case "users" rather than "aa".
The problem is in your listitem.xml file. Try to change to this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/icon" />
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:text="Description"
android:layout_below="#id/firstLine"
android:textSize="12sp" />
</RelativeLayout>