unable video thumbnails and show in a gridview android - java

I am developing a sharing app similar to Shareit, Xender. I want to show all the thumbnails of videos in a simple gridview but loading thumbnails takes a lot of time especially if I have more than a 1000 - 2000 videos.
So, I made a program to load each thumbnail on a new thread if it hasn't been loaded and then notify the base adapter.
The Code is :-
package com.*.filetransfer.Server.File.Selection.SubFragments;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.*.filetransfer.R;
import com.*.filetransfer.Strings;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.*.filetransfer.Server.File.Selection.FileSelection.selected_item_counter_down;
import static com.*.filetransfer.Server.File.Selection.FileSelection.selected_item_counter_up;
import static com.*.filetransfer.Server.File.Selection.FileSelection.videoList;
public class VideoGalleryFragment extends Fragment {
GridView gridView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridview, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
videoList = new ArrayList<Video>();
gridView = view.findViewById(R.id.gridview);
String[] projection = new String[] {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE
};
String selection = MediaStore.Video.Media.DURATION +
" >= ?";
String[] selectionArgs = new String[] {
String.valueOf(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MILLISECONDS))};
String sortOrder = MediaStore.Video.Media.DATE_ADDED + " DESC";
try (Cursor cursor = getContext().getApplicationContext().getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
sortOrder
)) {
// Cache column indices.
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
int nameColumn =
cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
int durationColumn =
cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
while (cursor.moveToNext()) {
// Get values of columns for a given video.
long id = cursor.getLong(idColumn);
String name = cursor.getString(nameColumn);
int duration = cursor.getInt(durationColumn);
long size = cursor.getLong(sizeColumn);
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
// Stores column values and the contentUri in a local object
// that represents the media file.
videoList.add(new Video(contentUri, name, duration, size, null, false, false));
}
gridView.setAdapter(new GalleryGridViewAdapter(requireContext(), videoList){
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if (imageView == null){
imageView = new ImageView(requireContext());
imageView.setLayoutParams(new GridView.LayoutParams(300,300));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(20,20,20,20);
}
if (( (Video) getItem(position)).isChecked()){
imageView.setBackgroundColor(getResources().getColor(R.color.aqua));
}
else{
imageView.setBackgroundColor(Color.TRANSPARENT);
}
if (((Video)getItem(position)).getThumbnail() == null && (!((Video)getItem(position)).isImageLoading())){
((Video)getItem(position)).setImageLoading(true);
new Thread(new Runnable() {
#Override
public void run() {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor1 = requireContext().getContentResolver().query(((Video)getItem(position)).getUri(), filePathColumn, null, null, null);
cursor1.moveToFirst();
int columnIndex = cursor1.getColumnIndex(filePathColumn[0]);
String picturePath = cursor1.getString(columnIndex);
cursor1.close();
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(picturePath, MediaStore.Video.Thumbnails.MINI_KIND);
((Video)getItem(position)).setThumbnail(bitmap);
((Video)getItem(position)).setImageLoading(true);
try {
requireActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
catch (IllegalStateException ignored){
}
}
}).start();
}
if (((Video)getItem(position)).getThumbnail() != null)
imageView.setImageBitmap(((Video)getItem(position)).getThumbnail());
return imageView;
}
});
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!videoList.get(position).isChecked()) {
videoList.get(position).setChecked(true);
selected_item_counter_up();
Log.e(Strings.TAG, String.valueOf(videoList.get(position).getSize()));
try {
((ImageView) view).setBackgroundColor(getResources().getColor(R.color.aqua));
} catch (Exception e) {
}
}
else{
videoList.get(position).setChecked(false);
selected_item_counter_down();
try {
((ImageView) view).setBackgroundColor(Color.TRANSPARENT);
} catch (Exception e) {
}
}
}
});
}
}
class GalleryGridViewAdapter extends BaseAdapter {
private List<Video> videos;
private Context context;
public GalleryGridViewAdapter(Context context, List<Video> videoList) {
this.context = context;
this.videos = videoList;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
The static methods and variable imported on top are :-
public static List<Video> videoList;
public static void selected_item_counter_up(){
selected_counter++;
view_counter.setText("Selected (" + selected_counter + ")");
}
public static void selected_item_counter_down(){
selected_counter--;
view_counter.setText("Selected (" + selected_counter + ")");
}
My video class is simple as follows:-
package com.*.filetransfer.Server.File.Selection.SubFragments;
import android.graphics.Bitmap;
import android.net.Uri;
public class Video {
private final Uri uri;
private final String name;
private final int duration;
private final long size;
private Bitmap thumbnail;
private boolean isImageLoading;
private boolean isChecked;
public Video(Uri uri, String name, int duration, long size, Bitmap bitmap, boolean isImageLoading, boolean isChecked) {
this.uri = uri;
this.name = name;
this.duration = duration;
this.size = size;
this.thumbnail = bitmap;
this.isImageLoading = isImageLoading;
this.isChecked = isChecked;
}
public boolean isChecked() {
return isChecked;
}
public boolean isImageLoading() {
return isImageLoading;
}
public Uri getUri() {
return uri;
}
public String getName() {
return name;
}
public int getDuration() {
return duration;
}
public long getSize() {
return size;
}
public Bitmap getThumbnail() {
return thumbnail;
}
public void setThumbnail(Bitmap thumbnail) {
this.thumbnail = thumbnail;
}
public void setImageLoading(boolean imageLoading) {
isImageLoading = imageLoading;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
The problem I am facing is, if the user scrolls too fast mostly all of the thumbnails are mixed up and some load multiple times. Can someone spot the flaw and correct it.
If you can please suggest an alternative way to load and show thumbnails of media on device, if possible seperated by date as I am unable to figure out how to do it
EDIT
I switched to recyclerview and it scrolls very smoothly but It is scrolling to top for some reason. Here is the updated code:-
package com.*.filetransfer.Server.File.Selection.SubFragments;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.sugarsnooper.filetransfer.R;
import com.*.filetransfer.Server.File.Selection.Media;
import com.*.filetransfer.Server.Send_Activity;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import static com.*.filetransfer.Server.File.Selection.FileSelection.imageList;
public class Photos extends Fragment {
RecyclerView gridView;
GridAdapter ga = new GridAdapter();
private int max_padding = 20;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridview, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new Thread(new Runnable() {
#Override
public void run() {
imageList = new ArrayList<>();
for (Map.Entry<String, Long> entry : Send_Activity.readableRoots.getImages().entrySet())
{
File file = new File(entry.getKey());
imageList.add(new Media(Uri.fromFile(file), file.getName(), file.length(), entry.getValue()));
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
gridView = view.findViewById(R.id.gridview);
gridView.setLayoutManager(new GridLayoutManager(requireContext(), 3));
gridView.setAdapter(ga);
gridView.addItemDecoration(new SpacesItemDecoration(30));
}
});
}
}).start();
}
class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
#Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
class GridAdapter extends RecyclerView.Adapter<GridAdapter.MyViewHolder> {
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(requireActivity()).inflate(R.layout.grid_item, parent, false);
return new MyViewHolder(layout);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
if (((Media) getItem(i)).isChecked()) {
holder.ivparent.setPadding(max_padding, max_padding, max_padding, max_padding);
holder.ivparent.setBackgroundColor(Color.parseColor("#777777"));
}
else{
holder.ivparent.setPadding(0, 0, 0, 0);
holder.ivparent.setBackgroundColor(Color.parseColor("#00777777"));
}
Glide.with(requireActivity()).fromUri().dontAnimate().load(((Media) getItem(i)).getUri()).into(holder.imageView);
}
#Override
public int getItemCount() {
return imageList.size();
}
#Override
public void onViewRecycled(#NonNull MyViewHolder holder) {
super.onViewRecycled(holder);
holder.recycle();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
LinearLayout ivparent;
ImageView imageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
ivparent = itemView.findViewById(R.id.iv_parent);
}
public void recycle() {
Glide.clear(imageView);
}
}
public Object getItem(int i) {
return imageList.get(i);
}
}
}

To achieve the same behavior I used Recyclerview + GridLayoutManager.
And loaded thumbnail from video uris using Glide inside onBindViewHolder.
So thumbnail for only items that are currently loaded in the screen gets created, and it handles async loading and clearing the views
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
// Code for loading thumbnail using video file path
Glide.with(context)
.load(Uri.fromFile(new File(videoFilePath)))
.thumbnail(0.5f)
.into(imageView);
}

Related

Why isn't onBindViewHolder getting called when I make a selection?

My scrolling list is displaying properly.
OnBindViewHolder is called for each item in initial display and when scrolling brings new items into view.
When I click on an item, I do see my ItemDetailsLookup and getItemDetails functions getting called, HOWEVER it doesn't call the OnBindViewHolder, and so setActivated isn't getting run.
The documentation for androidx.recyclerview.selection says "... When the user selects an item the library will record that in SelectionTracker then notify RecyclerView that the state of the item has changed. This will ultimately cause the value to be rebound by way of RecyclerView.Adapter#onBindViewHolder..." and I think I've done everything up to this point, but I must have missed something...
Any ideas?
Thanks
Here's my fragment:
package com.example.smartflashcards;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackSelectionFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
static SelectionTracker<Long> tracker;
public StackSelectionFragment() {
}
#SuppressWarnings("unused")
public static StackSelectionFragment newInstance(int columnCount) {
StackSelectionFragment fragment = new StackSelectionFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stack_selection_list, container, false);
File directory = getActivity().getFilesDir();
List<String> filesList = new ArrayList(Arrays.asList(directory.list()));
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(filesList));
recyclerView.getAdapter().hasStableIds();
this.tracker = new SelectionTracker.Builder<Long>(
"stack_selector",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).build();
}
return view;
}
final class MyDetailsLookup extends ItemDetailsLookup {
private final RecyclerView mRecyclerView;
MyDetailsLookup(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public #Nullable
ItemDetails getItemDetails(#NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder instanceof MyItemRecyclerViewAdapter.ViewHolder) {
return ((MyItemRecyclerViewAdapter.ViewHolder)holder).getItemDetails();
}
}
return null;
}
}
}
Here's my adapter:
package com.example.smartflashcards;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.smartflashcards.databinding.FragmentStackSelectionBinding;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<String> mValues;
public MyItemRecyclerViewAdapter(List<String> items) {
setHasStableIds(true);
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(FragmentStackSelectionBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = getItemId(position);
holder.mContentView.setText(mValues.get(position));
holder.mContentView.setActivated(StackSelectionFragment.tracker.isSelected((long) position));
}
#Override
public int getItemCount() {
return mValues.size();
}
#Override
public long getItemId(int position) {
return (long)position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mIdView;
public final TextView mContentView;
public Long mItem;
public ViewHolder(FragmentStackSelectionBinding binding) {
super(binding.getRoot());
mIdView = binding.itemNumber;
mContentView = binding.content;
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return mItem;
}
};
}
}
}
By following the example at https://github.com/Thumar/recyclerview-selection/tree/master/app
I was able to get it working. See my working code below.
But I still don't know which of the changes made it work and why.
If anyone figures out what was causing my problem, please post a comment or answer.
Any and all other feedback is welcome as well.
THANKS
Here's my new fragment:
package com.example.smartflashcards;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackSelectionFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
SelectionTracker<Long> tracker; //TODO: add private?
private StackSelectionListener listener;
public interface StackSelectionListener {
public void onSelectStack(String stack);
}
String selections = "";
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public StackSelectionFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static StackSelectionFragment newInstance(int columnCount) {
StackSelectionFragment fragment = new StackSelectionFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stack_selection_list, container, false);
File directory = getActivity().getFilesDir();
List<String> filesList = new ArrayList(Arrays.asList(directory.list()));
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
MyItemRecyclerViewAdapter adapter = new MyItemRecyclerViewAdapter(filesList);
recyclerView.setAdapter(adapter);
adapter.hasStableIds();
this.tracker = new SelectionTracker.Builder<Long>(
"stack_selector",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).build();
adapter.injectTracker(this.tracker);
SelectionTracker.SelectionObserver<Long> observer = new SelectionTracker.SelectionObserver<Long>() {
#Override
public void onSelectionChanged() {
super.onSelectionChanged();
//TODO: replace this placeholder action with something useful
selections = "";
tracker.getSelection().forEach(item -> selections += adapter.getContent(item.intValue()));//selections += item);
//listener.onSelectStack("selections"); //This causes an error???
Context context = getContext();
Toast toast = Toast.makeText(context, selections, Toast.LENGTH_LONG);
toast.show();
}
};
this.tracker.addObserver(observer);
}
return view;
}
final class MyDetailsLookup extends ItemDetailsLookup {
private final RecyclerView mRecyclerView;
MyDetailsLookup(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public #Nullable
ItemDetails getItemDetails(#NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder instanceof MyItemRecyclerViewAdapter.ViewHolder) {
return ((MyItemRecyclerViewAdapter.ViewHolder)holder).getItemDetails();
}
}
return null;
}
}
Here's my new adapter:
package com.example.smartflashcards;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<String> mValues;
private SelectionTracker<Long> selectionTracker;
public MyItemRecyclerViewAdapter(List<String> items) {
setHasStableIds(true); //TODO: remove redundancy between this and "recyclerView.getAdapter().hasStableIds()" in the Fragment
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_stack_selection, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String item = this.mValues.get(position);
holder.bind(item, selectionTracker.isSelected((long) position));
}
#Override
public int getItemCount() {
return mValues.size();
}
#Override
public long getItemId(int position) {
return (long)position;
}
public String getContent(int position) {
return mValues.get(position);
}
public void injectTracker(SelectionTracker<Long> tracker)
{
this.selectionTracker = tracker;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mContentView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mContentView = itemView.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
public void bind(String item, Boolean activate) {
this.mContentView.setText(item);
itemView.setActivated(activate); //TODO: understand how "itemView" exists outside of the constructor
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return (long) getAbsoluteAdapterPosition();
}
};
}
}
}

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 :)

Set ImageView color filter from adapter of RecyclerView

I try actually to set the imageView ColorFilter in a class which define the adapter avec the recyclerView. For that, I defined a ImageView ArrayList in my Adapter which stock my imageview from viewholder And I take them with a custom method with position parameter in my adapter too. But it doesn't really work, when I click on my items, the colorfilter is apply radomly on my recyclerviex items :/
This is my code :
The adapter :
package com.ylly.hypred.process.adapter;
/**
* Created by YLLY on 24/06/2015.
*/
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.ylly.hypred.process.recyclerView.ItemDataAtelier;
import com.ylly.hypred.R;
import com.ylly.hypred.custom.MyTextView;
import java.io.File;
import java.util.ArrayList;
public class AtelierAdapter extends RecyclerView.Adapter<AtelierAdapter.ViewHolder> {
private ArrayList<ItemDataAtelier> itemsData;
private Context context;
public AtelierAdapter(ArrayList<ItemDataAtelier> itemsData, Context context) {
this.itemsData = itemsData;
this.context = context;
}
// Create new views (invoked by the layout manager)
#Override
public AtelierAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/drawable/" + itemsData.get(position).getDrawable());
Picasso.with(context).load(R.drawable.hypred_atelier_atelier).into(viewHolder.imgViewIcon);
viewHolder.nomAtelierTextView.setText(itemsData.get(position).getLabel());
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgViewIcon;
public MyTextView nomAtelierTextView;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
nomAtelierTextView = (MyTextView) itemLayoutView.findViewById(R.id.item_layout_nom_atelier_textView);
}
}
// Return the size of your itemsData (invoked by the layout manager)
#Override
public int getItemCount() {
return itemsData.size();
}
}
My itemData :
package com.ylly.hypred.process.recyclerView;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
/**
* Created by YLLY on 07/07/2015.
*/
public class ItemDataCriteres {
private String label;
private int drawable;
private Boolean isActive;
private ImageView imageView;
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Boolean getIsActive() {
return isActive;
}
public ItemDataCriteres(String label, int drawable){
this.label = label;
this.drawable = drawable;
}
public void setLabel(String label) {
this.label = label;
}
public String getNomAtelier() {
return label;
}
public void setDrawable(int drawable) {
this.drawable = drawable;
}
public int getDrawable() {
return drawable;
}
public void setImageView(ImageView imageView) {
this.imageView = imageView;
}
public ImageView getImageView() {
return imageView;
}
}
And my class where I define my recyclerView and where I change the filter :
final CriteresAdapter criteresAdapter = new CriteresAdapter(itemDataDetailsEtThemes, v.getContext());
recyclerViewCriteresOne.setAdapter(criteresAdapter);
recyclerViewCriteresOne.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if (!criteresAdapter.getCritere(position).getIsActive()) {
criteresActifs[0]++;
setLancerRechercheTextViewVisibility(v);
criteresAdapter.getImageView(position).setColorFilter(v.getResources().getColor(R.color.hypred_gris), PorterDuff.Mode.MULTIPLY);
criteresAdapter.getCritere(position).setIsActive(true);
criteresAdapter.notifyDataSetChanged();
} else {
criteresActifs[0]--;
setLancerRechercheTextViewVisibility(v);
criteresAdapter.getImageView(position).clearColorFilter();
criteresAdapter.getCritere(position).setIsActive(false);
criteresAdapter.notifyDataSetChanged();
}
}
}));
Thanks in advance for your time :)
From the Drawable docs:
By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification.
The answer is to call Drawable.mutate()
A mutable drawable is guaranteed to not share its state with any other drawable.
I would change your ItemTouchListener to something like this:
recyclerViewCriteresOne.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Drawable drawable = criteresAdapter.getImageView(position);
drawable.mutate();
if (!criteresAdapter.getCritere(position).getIsActive()) {
criteresActifs[0]++;
setLancerRechercheTextViewVisibility(v);
drawable.setColorFilter(v.getResources().getColor(R.color.hypred_gris), PorterDuff.Mode.MULTIPLY);
criteresAdapter.getCritere(position).setIsActive(true);
criteresAdapter.notifyDataSetChanged();
} else {
criteresActifs[0]--;
setLancerRechercheTextViewVisibility(v);
drawable.clearColorFilter();
criteresAdapter.getCritere(position).setIsActive(false);
criteresAdapter.notifyDataSetChanged();
}
}
}));

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

"Set wallpaper" button function, Android

I've created a custom gallery; however, the "Set wallpaper" button will not set the wallpaper. Here's the wallpaper.java I have. I'm just lost on how to implement OnClickListener and then set my button to use an onclicklistener like so:
buttonName.setOnClickListener(this);
package com.totem;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Gallery.LayoutParams;
import java.io.IOException;
import java.io.InputStream;
public class Wallpaper extends Activity implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String LOG_TAG = "Home";
private static final Integer[] THUMB_IDS = {
R.drawable.andy_small,
};
private static final Integer[] IMAGE_IDS = {
R.drawable.andy,
};
private Gallery mGallery;
private boolean mIsWallpaperSet;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setOnItemClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#SuppressWarnings("unchecked")
public void onItemSelected(AdapterView parent, View v, int position, long id) {
getWindow().setBackgroundDrawableResource(IMAGE_IDS[position]);
}
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView parent, View v, int position, long id) {
selectWallpaper(position);
}
private synchronized void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(IMAGE_IDS[position]);
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to set wallpaper " + e);
}
}
#SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView parent) {
}
public boolean onTouchEvent(MotionEvent event, Object Action_Down) {
getAction(Action_Down);
selectWallpaper(mGallery.getSelectedItemPosition());
return true;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return THUMB_IDS.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(THUMB_IDS[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(android.R.drawable.picture_frame);
return i;
}
}
}
Parsed in 0.242 seconds, using GeSHi 1.0.8.4
Go to http://www.xtensivearts.com/topics/tutorials/ there are video tutorials that will help you with the onclicklisteners
are you set user permission in androidmanifest file for set Wallpaper?
<uses-permission android:name="android.permission.SET_WALLPAPER" />

Categories

Resources