How to speed up program that updates many UI items periodically? - java

I created a small application where I have a list of products and for each of the product I have an expiry time. If the user chooses to like a certain product(showTimerPost), the expiry time of the product will increase lets say 5 second. I tried it with a handler and it actually worked but my app started to run really slow maybe because it was changing the UI every second. I am really stuck with this problem for 1 month. Help will be appreciated.
package com.blueflair.incre;
import com.blueflair.incre.app.AppController;
import com.blueflair.incre.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
LocalUserData userLocalStore;
long postExpiry;
String timerFormat;
private int defaultPostIncrementation = 900000;
private List<FeedItem> feedItems;
boolean favourite;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private long timeDiff;
private final List<ViewHolder> lstHolders;
private int avatarSize;
Handler handler = new Handler();
private Runnable timerRunnable = new Runnable() {
#Override
public void run() {
for (final ViewHolder holder : lstHolders) {
holder.showTimerPost.postDelayed(new Runnable() {
#Override
public void run() {
long currentTime = System.currentTimeMillis();
currentTime--;
holder.showTimerPost.setText(String.valueOf(holder.updateTimeRemaining(currentTime)));
notifyDataSetChanged();
}
}, 2000);
}
}
};
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
lstHolders = new ArrayList<>();
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final FeedItem item = feedItems.get(position);
holder = new ViewHolder();
userLocalStore = new LocalUserData(activity);
final User user = userLocalStore.getLoggedInUser();
postExpiry = item.getPostExpiry();
avatarSize = activity.getResources().getDimensionPixelSize(R.dimen.feed_avater_size);
holder.name = (TextView) convertView.findViewById(R.id.userFeedName);
holder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
holder.statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
holder.profilePic = (ImageView) convertView
.findViewById(R.id.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args= new Bundle();
args.putInt("userId", item.getUserId());
Fragment profileViewFragment = new ProfileViewFragment();
profileViewFragment.setArguments(args);
FragmentTransaction ft = ((MainActivity)activity).getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_done, R.anim.slide_out_send);
ft.replace(R.id.container_body, profileViewFragment);
ft.addToBackStack(null);
ft.commit();
}
});
holder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
String username = "#"+item.getUserName();
holder.name.setText(username);
convertView.setTag(holder);
synchronized ( lstHolders) {
lstHolders.add(holder);
}
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeCreated()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.timestamp.setText(timeAgo);
holder.showTimerPost = (Button) convertView.findViewById(R.id.showPostTimer);
handler.post(timerRunnable);
holder.showTimerPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
item.setIncrementToExpiry(50000);
notifyDataSetChanged();
}
});
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getPostMessage())) {
holder.statusMsg.setText(item.getPostMessage());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Feed image
if (item.getUserImage() != null) {
holder.feedImageView.setImageUrl(item.getUserImage(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
//Setting the timer adapter for the post and their respective contents
holder.setData(item);
return convertView;
}
private class ViewHolder {
FeedItem item;
public TextView name;
public TextView timestamp;
public TextView statusMsg;
public ImageView profilePic;
public FeedImageView feedImageView;
public Button showTimerPost;
public void setData(FeedItem item) {
this.item = item;
updateTimeRemaining(System.currentTimeMillis());
}
public String updateTimeRemaining(long currentTime) {
timeDiff = (item.getPostExpiry()+400000000) - currentTime;
if (timeDiff > 0) {
timerFormat = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeDiff)));
showTimerPost.setText(timerFormat);
return timerFormat;
} else {
//Delete feed items when post is expired
showTimerPost.setText("Expired!");//only to explimify
}
return timerFormat;
}
}
}

Related

Listener from DialogFragment to Fragment

I'm a beginner in Java and I'm trying to create a listener in my DialogFragment to notice my fragment that some book was removed. When the user removes a book, I want to call the removeBook method in BookFragment and update the recyclerview.
Here is my BookDialogFragment.java:
package com.compose.dietapp.ui.books;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import java.util.Objects;
public class BookDialogFragment extends DialogFragment {
private final String nameToDelete;
private final int position;
private static String MESSAGE_TO_DIALOG_FRAGMENT;
public BookDialogFragment(String nameToDelete, int position) {
this.nameToDelete = nameToDelete;
this.position = position;
}
public static BookDialogFragment newInstance(String title, String nameToDelete, int position) {
BookDialogFragment frag = new BookDialogFragment(nameToDelete, position);
if (Objects.equals(nameToDelete, "none")) {
MESSAGE_TO_DIALOG_FRAGMENT = "Book removed!";
} else {
MESSAGE_TO_DIALOG_FRAGMENT = "Are you sure you want to remove the book '"
+ nameToDelete
+ "'?";
}
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
assert getArguments() != null;
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(MESSAGE_TO_DIALOG_FRAGMENT);
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
}
return alertDialogBuilder.create();
}
#Override
public void onStart() {
super.onStart();
((AlertDialog) Objects.requireNonNull(getDialog())).getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(Color.rgb(128, 128, 128));
}
}
And here is my BookFragment.java:
package com.compose.dietapp.ui.books;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import com.compose.dietapp.database.DatabaseAccess;
import com.compose.dietapp.databinding.FragmentBookBinding;
import java.util.ArrayList;
public class BookFragment extends Fragment{
#SuppressLint("StaticFieldLeak")
private static Activity activity;
private RecyclerView recyclerView;
private final ArrayList<Book> itensBook = new ArrayList<Book>();
private BookAdapter bookAdapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
activity = this.getActivity();
View v = inflater.inflate(R.layout.fragment_book, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.book_recycler);
instanciateBooks();
return v;
}
private void instanciateBooks() {
ArrayList<ArrayList<String>> bookDatabaseValues = getDatabaseData();
if (recyclerView != null && bookDatabaseValues != null) {
createItemBook(bookDatabaseValues);
createRecyclerViewBook();
}
}
public void removeBook(String nameToDelete, int position) {
getChildFragmentManager().setFragmentResultListener("removed",
this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
String result = bundle.getString("value");
Log.i("result", result);
}
});
}
private void createRecyclerViewBook() {
recyclerView.setHasFixedSize(true);
bookAdapter = new BookAdapter(activity, itensBook);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity,
LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(bookAdapter);
}
private void createItemBook(ArrayList<ArrayList<String>> bookDatabaseValues) {
for (int i = 0; i < bookDatabaseValues.size(); i++) {
itensBook.add(new Book(
String.valueOf(bookDatabaseValues.get(i).get(0)),
String.valueOf(bookDatabaseValues.get(i).get(1)),
String.valueOf(bookDatabaseValues.get(i).get(2)),
String.valueOf(bookDatabaseValues.get(i).get(3)),
String.valueOf(bookDatabaseValues.get(i).get(4))
));
}
}
public static ArrayList<ArrayList<String>> getDatabaseData() {
if (activity != null) {
return getArrayListsFromDatabase();
}
return null;
}
private static ArrayList<ArrayList<String>> getArrayListsFromDatabase() {
DatabaseAccess databaseAccess = openDatabase();
ArrayList<ArrayList<String>> books = databaseAccess.getBook();
closeDatabase(databaseAccess);
return books;
}
private static void closeDatabase(DatabaseAccess databaseAccess) {
databaseAccess.close();
}
#NonNull
private static DatabaseAccess openDatabase() {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(activity);
databaseAccess.open();
return databaseAccess;
}
}
Here is my BookAdapter.java:
package com.compose.dietapp.ui.books;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import java.io.InputStream;
import java.util.ArrayList;
public class BookAdapter extends RecyclerView.Adapter<BookViewHolder> {
public static FragmentManager supportFragment;
private final Context context;
private final ArrayList<Book> itens;
public BookAdapter(Context context, ArrayList<Book> itens) {
this.context = context;
this.itens = itens;
}
#NonNull
#Override
public BookViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_recycler_book, parent, false);
BookViewHolder viewHolder = new BookViewHolder(view);
supportFragment = ((AppCompatActivity)context).getSupportFragmentManager();
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull BookViewHolder bookViewHolder, int position) {
Book book = itens.get(position);
bookViewHolder.nome.setText(book.getName());
bookViewHolder.bookType.setText(book.getBookType());
imageInstanciate(bookViewHolder);
}
private void imageInstanciate(#NonNull BookViewHolder bookViewHolder) {
new DownloadImageFromInternet((ImageView) bookViewHolder.bookImage)
.execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
private class DownloadImageFromInternet extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageFromInternet(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String imageURL = urls[0];
Bitmap bimage = null;
try {
InputStream in = new java.net.URL(imageURL).openStream();
bimage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error Message", e.getMessage());
e.printStackTrace();
}
return bimage;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
#Override
public int getItemCount() {
return itens.size();
}
}
Here is my BookViewHolder.java:
package com.compose.dietapp.ui.books;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
public class BookViewHolder extends RecyclerView.ViewHolder {
TextView nome;
TextView bookType;
ImageView bookImage;
public BookViewHolder(#NonNull View itemView) {
super(itemView);
nome = itemView.findViewById(R.id.nome);
bookType = itemView.findViewById(R.id.email);
bookImage = itemView.findViewById(R.id.book_image);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int position = getLayoutPosition();
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nomeDelete = nome.getText().toString();
int position = getLayoutPosition();
FragmentManager fm = BookAdapter.supportFragment;
BookDialogFragment bookDialogFragment =
BookDialogFragment.newInstance("Atenção:", nomeDelete, position);
bookDialogFragment.show(fm, "fragment_alert");
}
});
}
}
I've seen other similar solutions, but I didn't get to implement them in my code. Can anyone help me?
Going through your code, it doesn't seem like you're using Navigation Component. So let's do it this way.
Your BookDialogFragment is a child fragment to BookFragment. So basically, you should set a result in your dialog when remove button is clicked. Then set up a result listener code in you parent fragment (BookFragment), so as to get immediate result to act upon.
First part, set a result when remove is clicked
NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
...
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
...
}
}
}
Then, listen for and act on the result in you BookFragment, wherever you want to, with these lines.
getChildFragmentManager().setFragmentResultListener("removed", this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
// We use a Boolean here, but any type that can be put in a Bundle is supported
Boolean result = bundle.getString("value");
// Do something with the result
}
});
PS: You can use constant variables where you have "removed" and "value" for accuracy.
Hope this helps :)

Problem with Clicking Items in RecyclerView

This is one of my tab fragment.
I just wanted to show the list of Movies & Tv Shows that includes the word in SearchView
And when I click one of the images, it moves to the Detail Activity.
The problem happens when I search two or more words continuously.
It moves to proper Detail Activity and when I close that Activity it comes with several other unrelated Detail Activity.
I need you guys help
First code is the Fragment Code
package com.example.endterm.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.endterm.ItemAdapter;
import com.example.endterm.Items;
import com.example.endterm.MovieDetail;
import com.example.endterm.R;
import com.example.endterm.TVDetail;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
SearchView searchView;
TextView tVQuery;
String queryWord;
//RecyclerView recyclerView7, recyclerView8;
ItemAdapter adapter7 = new ItemAdapter(7);
ItemAdapter adapter8 = new ItemAdapter(8);
public SearchFragment() {
// Required empty public constructor
}
class MyItmeDecoration extends RecyclerView.ItemDecoration{
#Override
public void getItemOffsets(#NonNull Rect outRect, #NonNull View view, #NonNull RecyclerView parent, #NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.set(10, 10, 10, 10);
view.setBackgroundColor(Color.BLACK);
}
}
// TODO: Rename and change types and number of parameters
public static SearchFragment newInstance(String param1, String param2) {
SearchFragment fragment = new SearchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_search, container, false);
tVQuery = (TextView) rootView.findViewById(R.id.query);
searchView = (SearchView) rootView.findViewById(R.id.search);
//final MyItmeDecoration Deco = new MyItmeDecoration();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
queryWord = s;
tVQuery.setText("Searched by : " + s);
// 입력받은 문자열 처리
searchView.onActionViewCollapsed();
adapter7.empty();
adapter8.empty();
adapter7.notifyDataSetChanged();
adapter8.notifyDataSetChanged();
exp(adapter7, "https://api.themoviedb.org/3/search/movie?api_key=0a9a6b6bcc6ed2a798fb5401045dd81f&language=ko&query=" + s + "&page=1&include_adult=false", true);
exp(adapter8, "https://api.themoviedb.org/3/search/tv?api_key=0a9a6b6bcc6ed2a798fb5401045dd81f&language=ko&page=1&query=" + s + "&include_adult=false", false);
return true;
}
#Override
public boolean onQueryTextChange(String s) {
// 입력란의 문자열이 바뀔 때 처리
return false;
}
});
return rootView;
}
private void exp(final ItemAdapter adapterS, String urlE, final boolean movieortv){
final RecyclerView rec;
if(movieortv) {
rec = (RecyclerView) getActivity().findViewById(R.id.searchedMovie);
}
else{
rec = (RecyclerView) getActivity().findViewById(R.id.searchedTV);
}
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rec.setLayoutManager(linearLayoutManager);
MyItmeDecoration Deco = new MyItmeDecoration();
if(Deco != null){
rec.removeItemDecoration(Deco);
}
rec.addItemDecoration(Deco);
rec.setAdapter(adapterS);
RequestQueue queue= Volley.newRequestQueue(getActivity());
StringRequest fR=new StringRequest(Request.Method.GET, urlE, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
parseXMLForecast(rec, response, adapterS, movieortv);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(fR);
}
private void parseXMLForecast(RecyclerView rec, String response, ItemAdapter adaptersample, final boolean movieortv){
try{
final ArrayList<Items> items = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
String results = jsonObject.getString("results");
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject subJsonObject = jsonArray.getJSONObject(i);
String url = "https://image.tmdb.org/t/p/w300" + subJsonObject.getString("poster_path");
String title;
if(movieortv) {
title = subJsonObject.getString("title");
}
else{
title = subJsonObject.getString("name");
}
String id = subJsonObject.getString("id");
Items jump = new Items(url, title, id);
items.add(jump);
}
adaptersample.setItems(items);
adaptersample.notifyDataSetChanged();
rec.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rec, new ClickListener() {
#Override
public void onClick(View view, int position) {
Items dict = items.get(position);
Intent intent;
if(movieortv == true) {
intent = new Intent(getActivity(), MovieDetail.class);
}
else{
intent = new Intent(getActivity(), TVDetail.class);
}
intent.putExtra("id", dict.getId());
intent.putExtra("url", dict.getUrl());
intent.putExtra("title", dict.getTitle());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
Items dict = items.get(position);
Toast.makeText(getActivity(), dict.getTitle()+' '+dict.getId()+' '+dict.getUrl(), Toast.LENGTH_LONG).show();
}
}));
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private SearchFragment.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final SearchFragment.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
And the Second one is the Adapter Code if you need
package com.example.endterm;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.endterm.Items;
import java.util.ArrayList;
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
private ArrayList<Items> items = new ArrayList<>();
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
private int wheree;
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public ItemAdapter(int wheree){
this.wheree = wheree;
}
public ItemAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View itemView = null;
if(wheree == 1) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork1, parent, false);
}
else if(wheree == 2){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork2, parent, false);
}
else if(wheree == 3){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork3, parent, false);
}
else if(wheree == 4){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork4, parent, false);
}
else if(wheree == 5){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork5, parent, false);
}
else if(wheree == 6){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork6, parent, false);
}
else if(wheree == 7){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork7, parent, false);
}
else if(wheree == 8){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork8, parent, false);
}
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
public void onBindViewHolder(#NonNull ItemAdapter.ViewHolder viewHolder, int position) {
Items item = items.get(position);
Glide.with(viewHolder.itemView.getContext())
.load(item.getUrl())
.into(viewHolder.weatherImageView);
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView weatherImageView;
public ViewHolder(View itemView){
super(itemView);
if(wheree == 1){
weatherImageView=(ImageView)itemView.findViewById(R.id.item_image1);
}
else if(wheree == 2){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image2);
}
else if(wheree == 3){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image3);
}
else if(wheree == 4){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image4);
}
else if(wheree == 5){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image5);
}
else if(wheree == 6){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image6);
}
else if(wheree == 7){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image7);
}
else if(wheree == 8){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image8);
}
}
}
public void empty(){
for(int i = 0; i < getItemCount(); i++){
items.remove(0);
}
}
public int getItemCount() {
return items.size();
}
public void setItems(ArrayList<Items> items){
this.items = items;
}
}
First of all, remove this code, you do not need this here
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
Then, you did not implement getItemId() correctly. You can change this like that:
#Override
public long getItemId(int position) {
return items.get(position).getId(); //if you have item id, of course
}
I think the problem is because you are not specifying the items id, that is why it is opening several activities. Try this out. Hope it helps

How to save steps after clicking on List Items

First of all sorry if the title is not suitable for my case,first I have a list view in fragment which have an adapter class components my list is looks like this ,thats if I click on menu Item it will increase the quantity by every click thats shown in that small orange box,my problem is that when I scroll this list or even change the activity it doesn't save the click that I did like this the quantity is backed to 0,all I need I just want to save this clicked action as
this is my adapter class
package abtech.waiteriano.com.waitrer.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.fragments.LVMenuFragment;
/**
* Created by dell on 3/7/2017.
*/
public class CustomMenuLVAdapter extends BaseAdapter {
ArrayList<String> resultMenuItems;
LVItemHolder lvItemHolder;
Context context;
private static LayoutInflater inflater = null;
public CustomMenuLVAdapter(LVMenuFragment lvMenuFragment, ArrayList<String> listMenuArray) {
resultMenuItems = listMenuArray;
context = lvMenuFragment.getActivity();
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultMenuItems.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class LVItemHolder {
TextView listMenuTV, txtQTY;
RelativeLayout qtyView;
Button minusBtn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final LVItemHolder lvItemHolder = new LVItemHolder();
View rowView;
rowView = inflater.inflate(R.layout.menu_list_item, null);
lvItemHolder.listMenuTV = (TextView) rowView.findViewById(R.id.menulistTV2);
lvItemHolder.txtQTY = (TextView) rowView.findViewById(R.id.txtQTY);
lvItemHolder.minusBtn = (Button) rowView.findViewById(R.id.minusBtn);
lvItemHolder.listMenuTV.setText(resultMenuItems.get(position));
lvItemHolder.txtQTY.setText("0");
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
q++;
lvItemHolder.txtQTY.setText("" + q);
// Toast.makeText(context, "You Clicked "+resultMenuItems.get(position), Toast.LENGTH_LONG).show();
}
});
lvItemHolder.minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
if (q > 0)
q--;
lvItemHolder.txtQTY.setText("" + q);
}
});
return rowView;
}
}
this is my Activity
package abtech.waiteriano.com.waitrer.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import abtech.waiteriano.com.waitrer.MenuActivity;
import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuLVAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;
public class LVMenuFragment extends android.app.Fragment {
View rootView;
ListView menuListView;
public static ArrayList<String> listMenuArray = new ArrayList<String>();
public LVMenuFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_lvmenu, container, false);
menuListView=(ListView) rootView.findViewById(R.id.listView);
listMenuArray.clear();
String menuListSTR = "";
if (MenuActivity.Prst_ID.trim() == "-1")
menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
else
menuListSTR = "select dbo.MenuItems.Item_ID, dbo.Items.Code, dbo.Items.Name, dbo.Items.Name2, dbo.Items.PrintOnChick, dbo.Items.Taxable, dbo.Items.NoServiceCharge, dbo.Items.PrintOnReport,Case { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), 0) } when 0 then dbo.Items.StaticPrice Else { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), dbo.Items.StaticPrice) } END AS Price From dbo.MenuItems LEFT OUTER JOIN dbo.Items ON dbo.MenuItems.Item_ID = dbo.Items.ID Where (dbo.MenuItems.Preset_ID = " + MenuActivity.Prst_ID + ") AND (dbo.MenuItems.Rest_ID_Active = " + ConnectionClass.Rest_ID + ") AND (dbo.MenuItems.OutLet_ID_Active = " + ConnectionClass.OutletID + ") AND (dbo.Items.Active = 1) ORDER BY dbo.MenuItems.SortNumber";
ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
try {
while (rs.next()) {
listMenuArray.add(rs.getString("Name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
menuListView.setAdapter(new CustomMenuLVAdapter(this,listMenuArray));
return rootView;
}
}
Sorry if any thing is unclear
Use this
public class CustomMenuLVAdapter extends BaseAdapter {
ArrayList<String> resultMenuItems;
LVItemHolder lvItemHolder;
Context context;
private static LayoutInflater inflater = null;
HashMap<Integer, Integer> map = new HashMap<>;
public CustomMenuLVAdapter(LVMenuFragment lvMenuFragment, ArrayList<String> listMenuArray) {
resultMenuItems = listMenuArray;
context = lvMenuFragment.getActivity();
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultMenuItems.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class LVItemHolder {
TextView listMenuTV, txtQTY;
RelativeLayout qtyView;
Button minusBtn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final LVItemHolder lvItemHolder = new LVItemHolder();
View rowView;
rowView = inflater.inflate(R.layout.menu_list_item, null);
lvItemHolder.listMenuTV = (TextView) rowView.findViewById(R.id.menulistTV2);
lvItemHolder.txtQTY = (TextView) rowView.findViewById(R.id.txtQTY);
lvItemHolder.minusBtn = (Button) rowView.findViewById(R.id.minusBtn);
lvItemHolder.listMenuTV.setText(resultMenuItems.get(position));
if(map.containsKey(position)){
lvItemHolder.txtQTY.setText(""+map.get(position));
}else{
lvItemHolder.txtQTY.setText("0");
}
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
q++;
lvItemHolder.txtQTY.setText("" + q);
map.put(position,q)
// Toast.makeText(context, "You Clicked "+resultMenuItems.get(position), Toast.LENGTH_LONG).show();
}
});
lvItemHolder.minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
if (q > 0)
q--;
lvItemHolder.txtQTY.setText("" + q);
map.put(position,q)
}
});
return rowView;
}
in your adapter have a funtion like the following as an example;
public void setNumber(int number) {this.number = number}
Then when the user clicks on an item to increase it, you can save it by calling this setNumber function.
resultMenuItems.get(position).setNumber(//you number inputed here//);
//Then call notifydatasetChanged on your adapter//
Just make sure that the number is then gotten through a getter function in the apater.
I hope this makes sense

How to make a custom listview clickable

I'm having trouble making a listview item clickable. I've tried if statments, onclicklisteners and I'm still not having any success, does anyone know how to do this? I also have another class to get the strings, but I don't think it is needed. If you could help me out with this, I would appreciate it! Thanks!Here is my code:
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity{
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.row, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(MainActivity.this,
"Please wait...", "Retrieving data ...", true);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
m_orders = new ArrayList<Order>();
Order o1 = new Order();
o1.setOrderName("Item 1");
o1.setOrderStatus("2012");
o1.setorderpic(R.drawable.bulb);
Order o2 = new Order();
o2.setOrderName("Item 2");
o2.setOrderStatus("Completed");
o2.setorderpic(R.drawable.bulb);
m_orders.add(o1);
m_orders.add(o2);
Thread.sleep(5000);
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Order o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
ImageView ct = (ImageView) v.findViewById(R.id.icon);
if (tt != null) {
tt.setText("Name: "+o.getOrderName()); }
if(bt != null){
bt.setText("Status: "+ o.getOrderStatus());
}
if(ct !=null){
ct.setImageResource(o.getorderpic());
}
}
return v;
}
}
You can use view's OnClickListener in getView() of your custom adapter
v.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// do something on click
}
});
http://developer.android.com/reference/android/view/View.OnClickListener.html
You should override ListActivity's onListItemClick method. This is what ListActivity is made for.
onListItemClick()

Add TextView to ListView Item

I need to add ListView items that can contain different count of TextView and Imageview objects. How can I do it? And how to determine and setup the id's of this objects? When I try to add an ImageView or TextView to LinearLayout with id R.id.chat_message, the application crashes :(
package com.me.my_app;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendSendMessageActivity extends ListActivity {
ListView view;
public ContactAdapter contactAdapter;
LinearLayout LL;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_send_message);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int index = Integer.parseInt(extras.get(getPackageName() + ".IndexInList").toString());
String sentFrom = extras.get(getPackageName() + ".SentFrom").toString();
int id = Integer.parseInt(extras.get(getPackageName() + ".Id").toString()); //либо id друга либо id друга
FriendItem.Friend item = TabFriendsActivity.getList().get(index);
view = getListView();
contactAdapter = new ContactAdapter();
contactAdapter.addItem(new MessageItem.Message(1, true, true, true, "123","13:31",new ArrayList<MessageItem.Message.Attachment>()));
ArrayList<MessageItem.Message.Attachment> list = new ArrayList<MessageItem.Message.Attachment>();
list.add(new MessageItem.Message.Attachment(MessageAttachmentType.PHOTO, RoundedImage.createRoundedPhoto(BitmapFactory.decodeResource(MainActivity.res,R.drawable.temp_user_photo))));
contactAdapter.addItem(new MessageItem.Message(1, true, true, true, "123","9:10",list));
view.setAdapter(contactAdapter);
}
}
class ContactAdapter extends BaseAdapter {
private ArrayList<MessageItem.Message> mData = new ArrayList<MessageItem.Message>();
private LayoutInflater mInflater;
private static final int IGNORE_ITEM_VIEW_TYPE = -1;
private static final int TYPE_ITEM = 0; //обычный item
private static final int TYPE_MAX_COUNT = 2; //макс. число layout'ов отображения item'ов
public ContactAdapter()
{
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final MessageItem.Message item) {
mData.add(item);
notifyDataSetChanged();
}
public int getItemViewType(int position)
{
return TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount()
{
return mData.size();
}
public MessageItem.Message getItem(int position)
{
return mData.get(position);
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int pos)
{
return true;
}
public View getView(int position, View convertView, ViewGroup parent) {
MessageItem.ViewHolder holder = null;
MessageItem.Message item = mData.get(position);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (convertView == null)
{
holder = new MessageItem.ViewHolder();
convertView = mInflater.inflate(item.in_out ? R.layout.chat_message_in_item : R.layout.chat_message_out_item, null, false);
if(item.listAttach.size() > 0)
holder.attachLL = (LinearLayout) findViewById(R.id.chat_message);
for(MessageItem.Message.Attachment attach : item.listAttach)
{
switch(attach.type)
{
case PHOTO:
if(attach.photo != null)
{
ImageView iv = new ImageView(convertView.getContext());
//iv.setLayoutParams(params);
iv.setId(0x7f000000 - 1);
holder.listAttach.add(new MessageItem.Message.Attachment(attach.type,iv));
Log.v("","1" + iv.getId() + " " + holder.listAttach.size());
}
else
Log.v("", "Null!");
break;
}
}
convertView.setTag(holder);
} else {
holder = (MessageItem.ViewHolder) convertView.getTag();
}
for(int i = 0; i < holder.listAttach.size();i++)
{
if(holder.listAttach.get(i).type == MessageAttachmentType.PHOTO && item.listAttach.get(i).photo != null && holder.listAttach.get(i).image != null)
{
holder.attachLL.addView(holder.listAttach.get(i).image);
holder.listAttach.get(i).image.setImageBitmap(item.listAttach.get(i).photo);
}
else
Log.v("", "Unable to add image!");
}
return convertView;
}
}
}
And MessageItem.java:
package com.me.my_app;
import java.util.ArrayList;
import java.util.Comparator;
import android.graphics.Bitmap;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MessageItem
{
public static class Message implements Comparator<Message>
{
int id;
boolean in_out;
boolean is_read;
boolean is_delivered;
String message;
String time;
ArrayList<Attachment> listAttach;
public Message(int id, boolean in_out, boolean is_read, boolean is_delivered, String message, String time, ArrayList<Attachment> list)
{
this.id = id;
this.in_out = in_out;
this.is_read = is_read;
this.is_delivered = is_delivered;
this.message = message;
this.time = time;
listAttach = new ArrayList<Attachment>();
if(list != null)
{
for(Attachment a : list)
listAttach.add(a);
}
}
public int compare(Message object1, Message object2) {
return object1.time.compareTo(object2.time);
}
public static class Attachment
{
ImageView image;
MessageAttachmentType type;
Bitmap photo;
String Uri;
public Attachment(MessageAttachmentType type, Bitmap photo)
{
this.type = type;
this.photo = photo;
}
public Attachment(MessageAttachmentType type, ImageView image)
{
this.type = type;
this.image = image;
}
}
}
public static class ViewHolder
{
LinearLayout attachLL;
TextView text, time;
ArrayList<MessageItem.Message.Attachment> listAttach;
public ViewHolder()
{
listAttach = new ArrayList<MessageItem.Message.Attachment>();
}
}
}
enter code here
You will most probably have to implement your own list view adapter. Then you can create any layout for your item and set it up. Here is how it's done in my code:
public class ExpAdapter extends BaseExpandableListAdapter {
/*SOME CODE HERE*/
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_row, null);
}
int groupId = ((ListTaskElement)this.getGroup(groupPosition)).id;
this.setupTaskView(convertView, this.childrenOfGroup(groupId, false).get(childPosition));
convertView.setTag(this.getChildId(groupPosition, childPosition));
return convertView;
}
/*SOME CODE HERE*/
}
You can find all the details here: http://jnastase.alner.net/archive/2010/12/19/custom-android-listadapter.aspx

Categories

Resources