Converting traditional Gallery to GridView on Wallpaper Selector - java

im trying to figure out how i can make this work. I have perfectly working wallpaper selector, Which loads the wallpaper as a [1]:https://www.dropbox.com/s/phu0a6atue7vlsb/Screenshot_2013-01-03-23-35-06.png
However im trying to change the code to look something like this!
The main interface like so.
https://www.dropbox.com/s/0v0wd9sx41nh2oh/Screenshot_2013-01-03-23-38-34.png
And when the "Wallpaper" is selected it bring up a ImageView of the large wallpaper
https://www.dropbox.com/s/dna7xxa1hzywwme/Screenshot_2013-01-03-23-38-55.png
Here is what i have for soure code.
Im suck on getting it changed from a Gallery to a GridView!
WallpaperChooser.java
public class WallpaperChooser extends Activity {
#SuppressWarnings("unused")
private static final String TAG = "Launcher.WallpaperChooser";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper_chooser_base);
Fragment fragmentView =
getFragmentManager().findFragmentById(R.id.wallpaper_chooser_fragment);
// TODO: The following code is currently not exercised. Leaving it here in case it
// needs to be revived again.
if (fragmentView == null) {
/* When the screen is XLarge, the fragment is not included in the layout, so show it
* as a dialog
*/
DialogFragment fragment = WallpaperChooserDialogFragment.newInstance();
fragment.show(getFragmentManager(), "dialog");
}
}
}
WallpaperChooserFragment.java
public class WallpaperChooserDialogFragment extends DialogFragment implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String TAG = "Launcher.WallpaperChooserDialogFragment";
private static final String EMBEDDED_KEY = "com.jaisonbrooks.theme.sony.xperia."
+ "WallpaperChooserDialogFragment.EMBEDDED_KEY";
private boolean mEmbedded;
private Bitmap mBitmap = null;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
private WallpaperDrawable mWallpaperDrawable = new WallpaperDrawable();
public static WallpaperChooserDialogFragment newInstance() {
WallpaperChooserDialogFragment fragment = new WallpaperChooserDialogFragment();
fragment.setCancelable(true);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(EMBEDDED_KEY)) {
mEmbedded = savedInstanceState.getBoolean(EMBEDDED_KEY);
} else {
mEmbedded = isInLayout();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(EMBEDDED_KEY, mEmbedded);
}
private void cancelLoader() {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
#Override
public void onDetach() {
super.onDetach();
cancelLoader();
}
#Override
public void onDestroy() {
super.onDestroy();
cancelLoader();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
/* On orientation changes, the dialog is effectively "dismissed" so this is called
* when the activity is no longer associated with this dying dialog fragment. We
* should just safely ignore this case by checking if getActivity() returns null
*/
Activity activity = getActivity();
if (activity != null) {
activity.finish();
}
}
/* This will only be called when in XLarge mode, since this Fragment is invoked like
* a dialog in that mode
*/
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
findWallpapers();
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
findWallpapers();
/* If this fragment is embedded in the layout of this activity, then we should
* generate a view to display. Otherwise, a dialog will be created in
* onCreateDialog()
*/
if (mEmbedded) {
View view = inflater.inflate(R.layout.wallpaper_chooser, container, false);
view.setBackground(mWallpaperDrawable);
final Gallery gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setCallbackDuringFling(false);
gallery.setOnItemSelectedListener(this);
gallery.setAdapter(new ImageAdapter(getActivity()));
View setButton = view.findViewById(R.id.set);
setButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
selectWallpaper(gallery.getSelectedItemPosition());
}
});
return view;
}
return null;
}
private void selectWallpaper(int position) {
try {
WallpaperManager wpm = (WallpaperManager) getActivity().getSystemService(
Context.WALLPAPER_SERVICE);
wpm.setResource(mImages.get(position));
Activity activity = getActivity();
activity.setResult(Activity.RESULT_OK);
activity.finish();
} catch (IOException e) {
Log.e(TAG, "Failed to set wallpaper: " + e);
}
}
// Click handler for the Dialog's GridView
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectWallpaper(position);
}
// Selection handler for the embedded Gallery view
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel();
}
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
// Context.getPackageName() may return the "original" package name,
// com.android.launcher2; Resources needs the real package name,
// com.android.launcher. So we ask Resources for what it thinks the
// package name should be.
final String packageName = resources.getResourcePackageName(R.array.wallpapers);
addWallpapers(resources, packageName, R.array.wallpapers);
// addWallpapers(resources, packageName, R.array.extra_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_thumb",
"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
// Log.d(TAG, "add: [" + packageName + "]: " + extra + " (" + res + ")");
}
}
}
}
private class ImageAdapter extends BaseAdapter implements ListAdapter, SpinnerAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(Activity activity) {
mLayoutInflater = activity.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
view = convertView;
}
ImageView image = (ImageView) view.findViewById(R.id.wallpaper_image);
int thumbRes = mThumbs.get(position);
image.setImageResource(thumbRes);
Drawable thumbDrawable = image.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error decoding thumbnail resId=" + thumbRes + " for wallpaper #"
+ position);
}
return view;
}
}
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(),
mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
// Help the GC
if (mBitmap != null) {
mBitmap.recycle();
}
View v = getView();
if (v != null) {
mBitmap = b;
mWallpaperDrawable.setBitmap(b);
v.postInvalidate();
} else {
mBitmap = null;
mWallpaperDrawable.setBitmap(null);
}
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
/**
* Custom drawable that centers the bitmap fed to it.
*/
static class WallpaperDrawable extends Drawable {
Bitmap mBitmap;
int mIntrinsicWidth;
int mIntrinsicHeight;
/* package */void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
if (mBitmap == null)
return;
mIntrinsicWidth = mBitmap.getWidth();
mIntrinsicHeight = mBitmap.getHeight();
}
public void draw(Canvas canvas) {
if (mBitmap == null) return;
int width = canvas.getWidth();
int height = canvas.getHeight();
int x = (width - mIntrinsicWidth) / 2;
int y = (height - mIntrinsicHeight) / 2;
canvas.drawBitmap(mBitmap, x, y, null);
}
public int getOpacity() {
return android.graphics.PixelFormat.OPAQUE;
}
public void setAlpha(int alpha) {
// Ignore
}
public void setColorFilter(ColorFilter cf) {
// Ignore
}
}
}
Layouts
wallpaper_chooser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/pinstripe_actionbar_tile_white"
android:orientation="vertical" >
<ImageView
android:id="#+id/wallpaper"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1.0"
android:scaleType="fitCenter" />
<Gallery
android:id="#+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/wallpaper_instructions"
android:textColor="#color/roboto" />
</LinearLayout>
wallpaper_item.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/wallpaper_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/gallery_item_background"
android:scaleType="fitXY"
android:focusable="true" />
I've should some of the following resources
GridView | Android Developers:http://developer.android.com/guide/topics/ui/layout/gridview.html
And a few others, I attempt to change everything over put end up bricking the entire code.
Any Help by Tips, Code, Example, Links, Support i'd extremely appreciate it all, Thank you.

Related

Android Tv RecyclerView focus Jumps

I am developing android app for Android Tv. I have a RecyclerView in which there are items that can be iterated over using the remote control (D-pad). When I reach the end of the RecyclerView, the focus (the stroke around the item in the RecyclerView) jumps or flies off the RecyclerView. I want the focus to stop at the end. Thanks in advance
My fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TV.TvPopularFragment">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminateDrawable="#drawable/progress_circle_style"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/moviesRecyclerView"
android:layout_width="match_parent"
android:nextFocusDown="#+id/moviesRecyclerView"
android:descendantFocusability="afterDescendants"
android:layout_height="match_parent"/>
</RelativeLayout>
My fragment.java
package org.vitaliy.moziapp.TV;
public class TvPopularFragment extends Fragment {
FragmentTvPopularBinding binding;
static public boolean isPopularOnTop = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentTvPopularBinding.inflate(inflater, container, false);
View root = binding.getRoot();
RecyclerView moviesRecycerView = binding.moviesRecyclerView;
ProgressBar progressBar = binding.progressBar;
Display display = getActivity().getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpWidth = outMetrics.widthPixels / density;
int columns = Math.round(dpWidth/133);
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(),columns);
moviesRecycerView.setLayoutManager(mLayoutManager);
PopularAdapter popularAdapter = new PopularAdapter(getActivity(),popular_posters,
popular_title, popular_id, popular_categories, popular_votes_pos, popular_votes_neg,
popular_last_episode);
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
if(AppActivity.isPopularCategoryLoaded) {
moviesRecycerView.setAdapter(popularAdapter);
progressBar.setVisibility(View.GONE);
cancel();
}
}
public void onFinish() {
}
}.start();
moviesRecycerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int totalItemCount = mLayoutManager.getItemCount();
int lastVisible = mLayoutManager.findLastVisibleItemPosition();
boolean endHasBeenReached = lastVisible + 15 >= totalItemCount;
isPopularOnTop = dy == 0;
if (totalItemCount > 0 && endHasBeenReached) {
if(AppActivity.popularHasNextPage) {
AppActivity.popularPage += 1;
AppActivity.loadPopularCategory();
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
if(AppActivity.isPopularCategoryLoaded) {
progressBar.setVisibility(View.GONE);
popularAdapter.notifyDataSetChanged();
}
}
public void onFinish() {
}
}.start();
AppActivity.popularHasNextPage = false;
}
}
}
});
return root;
}
}
My adapter.java:
package org.vitaliy.moziapp.PopularFragment;
public class PopularAdapter extends RecyclerView.Adapter<PopularViewHolder> {
static public String current_id;
static public String current_category;
ArrayList<String> movies_posters;
ArrayList<String> movies_title;
ArrayList<String> movies_id;
ArrayList<String> movies_categories;
ArrayList<String> movies_votes_pos;
ArrayList<String> movies_votes_neg;
ArrayList<String> movies_last_episode;
LayoutInflater inflater;
Context context;
public PopularAdapter(Context context, ArrayList<String> movies_posters,
ArrayList<String> movies_title,
ArrayList<String> movies_id,
ArrayList<String> movies_categories,
ArrayList<String> movies_votes_pos,
ArrayList<String> movies_votes_neg,
ArrayList<String> movies_last_episode){
this.movies_posters = movies_posters;
this.movies_title = movies_title;
this.movies_id = movies_id;
this.movies_categories = movies_categories;
this.movies_votes_pos = movies_votes_pos;
this.movies_votes_neg = movies_votes_neg;
this.movies_last_episode = movies_last_episode;
this.context = context;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public PopularViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_movie, parent, false);
return new PopularViewHolder(view);
}
#SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
#Override
public void onBindViewHolder(#NonNull PopularViewHolder holder, #SuppressLint("RecyclerView") int position) {
if(movies_categories.get(position).equals("s7")||
movies_categories.get(position).equals("s93")) {
holder.movie_last_episode.setVisibility(View.VISIBLE);
holder.movie_last_episode.setText(movies_last_episode.get(position));
} else {
holder.movie_last_episode.setVisibility(View.GONE);
}
Picasso.with(context).load(movies_posters.get(position))
.into(holder.movie_poster, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
holder.movie_icon.setVisibility(View.VISIBLE);
}
});
holder.movie_title.setText(Html.fromHtml(movies_title.get(position)));
holder.movie_btn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
holder.movie_title.setSelected(b);
}
});
holder.movie_votes_pos.setText(movies_votes_pos.get(position));
holder.movie_votes_neg.setText(movies_votes_neg.get(position));
holder.movie_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
current_id = movies_id.get(position);
current_category = movies_categories.get(position);
AppActivity.current_id = current_id;
MovieVideosFragment.category = current_category;
VideosAdapter.category = current_category;
if (current_category.equals("s7") || current_category.equals("s93"))
AppActivity.loadSeriesAudio(current_id);
else
AppActivity.loadMoviesAudio(current_id);
AppActivity.isMoviesLoaded = false;
AppActivity.isSeriesLoaded = false;
MovieFragment.year = null;
MovieFragment.actors = null;
MovieFragment.genres = null;
MovieFragment.countries = null;
MovieFragment.short_story = null;
AppActivity.loadMovieDescription(current_id);
AppActivity.loadSimilar(current_id);
MovieFragment.poster = movies_posters.get(position);
MovieFragment.title = movies_title.get(position);
context.startActivity(new Intent(context, MovieTab.class));
}
});
}
#Override
public int getItemCount() {
return movies_posters.size();
}
}

How do I determine which card view is clicked on the recycelview layout?

For instance, I have a UI which consists of two CardView per recycleView "position" as shown below:
Image
Whilst using the recycleview.view holder, I can determine the position at which the user clicked the screen by using the "getAdapterPosition()" onClick method but I am not able to determine which card view it was, i.e left or the right card view ( for instance in this Image example - given the position was 0, I am not able to determine if it was either "podcast" or "charts")
How do I determine which cardview the user has clicked -i.e left or right?
Below is my code for the RecycleViewAdpater:
public class DisplayGenresRecyclerViewAdapter extends RecyclerView.Adapter<DisplayGenresRecyclerViewAdapter.ViewHolder> {
// Cursor cursor = null;
Context context;
ArrayList<SuperGenreDouble> uniqueGenre;
private LayoutInflater inflater;
private ItemClickListener clickListener;
public DisplayGenresRecyclerViewAdapter(Context context, ArrayList<SuperGenreDouble> uniqueGenre) {
this.context = context;
this.inflater = LayoutInflater.from(context);
this.uniqueGenre = uniqueGenre;
}
public static String toTitleCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
public static String removeSpacing(String givenString) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < givenString.length(); i++) {
if (!givenString.contains(" ")) {
sb.append(givenString.charAt(i));
}
}
return sb.toString().trim();
}
public static int getDominantColor(Bitmap bitmap) {
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 1, 1, true);
final int color = newBitmap.getPixel(0, 0);
newBitmap.recycle();
return color;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.display_super_genres_recycle_view_container, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String path;
String genreRight = uniqueGenre.get(position).superGenre1;
String imageArtistRight = uniqueGenre.get(position).superGenreImageUrl1;
String genreLeft = uniqueGenre.get(position).superGenre2;
String imageArtistLeft = uniqueGenre.get(position).superGenreImageUrl2;
if (genreLeft != null) {
holder.textViewLeft.setText(toTitleCase(genreLeft));
try {
// get the image
Picasso.get().load(imageArtistLeft).into(holder.imageGenreLeft, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
// set the color
Bitmap bitmap = ((BitmapDrawable) holder.imageGenreLeft.getDrawable()).getBitmap();
int color = getDominantColor(bitmap);
holder.cardColourLeft.setBackgroundColor(color);
holder.textViewLeft.setTextColor(lightenColor(color));
}
#Override
public void onError(Exception e) {
}
});
} catch (Exception e) {
}
}
if (genreRight != null) {
holder.textViewRight.setText(toTitleCase(genreRight));
try {
// get the image
Picasso.get().load(imageArtistRight).into(holder.imageGenreRight, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
// set the color
Bitmap bitmap = ((BitmapDrawable) holder.imageGenreRight.getDrawable()).getBitmap();
int color = getDominantColor(bitmap);
holder.cardColourRight.setBackgroundColor(color);
holder.textViewRight.setTextColor(lightenColor(color));
}
#Override
public void onError(Exception e) {
}
});
} catch (Exception e) {
}
}
}
#ColorInt
int lightenColor(#ColorInt int color) {
return Color.rgb(255-(color >> 8)&0xFF, 255-(color >> 8)&0xFF, 255-(color >> 8)&0xFF);
}
#Override
public int getItemCount() {
return uniqueGenre.size();
}
void setClickListener(ItemClickListener itemClickListener) {
Log.d("onBindViewHolder", "onBindViewHolder: length");
this.clickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewLeft;
TextView textViewRight;
ImageView imageGenreLeft;
ImageView imageGenreRight;
CardView cardColourRight;
CardView cardColourLeft;
ViewHolder(View itemView) {
super(itemView);
textViewLeft = itemView.findViewById(R.id.textViewLeft);
textViewRight = itemView.findViewById(R.id.textViewRight);
imageGenreLeft = itemView.findViewById(R.id.imageGenreLeft);
imageGenreRight = itemView.findViewById(R.id.imageGenreRight);
cardColourRight = itemView.findViewById(R.id.cardViewRight);
cardColourLeft = itemView.findViewById(R.id.cardViewLeft);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.d("myPos", getAdapterPosition());
}
}
}
When getting a position in a RecyclerViewyou must note that you are getting the position of the ViewHolder and not the View Elements inside the ViewHolder. So for your question what you can do is implement onClickListener for the Views you want as such:
ViewHolder(View itemView) {
cardColourRight = itemView.findViewById(R.id.cardViewRight);
cardColourLeft = itemView.findViewById(R.id.cardViewLeft);
//add these
cardColourRight.setOnClickListener(this);
cardColourLeft.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view == R.id.cardViewLeft){
//User has clicked Left
}
else if(view == R.id.cardViewRight){
//User has clicked Right
}
}

unable to fetch images in image slider in fragment

When I extend an Activity this works fine, but when extending ActivityFragment I get an error:
unable to resolve constructor
At this line: BaseViewPagerAdapter<String> adapter = new BaseViewPagerAdapter<String>(this). I'm just fetching the image from a URL and displaying it in an image slider. If anyone knows any links or tutorials feel free to suggest me. Thanks.
HomeActivity.java
public class HomeActivity extends Fragment {
private String[] paths = {"http://reviewsimpact.com/wp-content/uploads/2016/04/Patanjali-products-list-1024x385.png",
"https://4.bp.blogspot.com/-3-qgzGwoQ3o/Vuqb1a0g6RI/AAAAAAAAATc/FZjOTm0VUBgXsw3VnWz3RorARUUUgl32g/s1600/Baba%2BRamdev%2BPatanjali%2BProducts%2BList%2Bwith%2BPrice%2Blatest%2B-%2BTipsmonk.jpg",
"http://patanjalistores.com/wp-content/uploads/2015/08/maxresdefault-1920x692.jpg",
"https://aos.iacpublishinglabs.com/question/aq/700px-394px/poems-fruits-vegetables_8d6a91e11da7d63.jpg?domain=cx.aos.ask.com",
"https://i.ytimg.com/vi/2IVR8BrUESQ/maxresdefault.jpg"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
AutoScrollViewPager mViewPager = (AutoScrollViewPager) v.findViewById(R.id.viewPager);
mViewPager = (AutoScrollViewPager)v.findViewById(R.id.viewPager);
BaseViewPagerAdapter<String> adapter = new BaseViewPagerAdapter<String>(this) {
#Override
public void loadImage(ImageView view, int position, String url) {
Picasso.with(getActivity().getApplicationContext()).load(url).into(view);
}
#Override
public void setSubTitle(TextView textView, int position, String s) {
textView.setText("");
}
};
mViewPager.setAdapter(adapter);
adapter.add(initData());
return v;
}
private List<String> initData() {
List<String> data = new ArrayList<>();
Picture picture ;
for (int i = 0 ; i < paths.length ;i++){
data.add(paths[i]);
}
return data;
}
}
BaseBaseViewPagerAdapter.java
public abstract class BaseViewPagerAdapter<T> extends PagerAdapter implements ViewPager.OnPageChangeListener{
private List<T> data = new ArrayList<>();
private Context mContext;
private AutoViewPager mView;
private OnAutoViewPagerItemClickListener listener;
public BaseViewPagerAdapter(List<T> t) {
this.data = t;
}
public BaseViewPagerAdapter(Context context, OnAutoViewPagerItemClickListener listener) {
this.mContext = context;
this.listener = listener;
}
public BaseViewPagerAdapter(Context context, List<T> data) {
this.mContext = context;
this.data = data;
}
public BaseViewPagerAdapter(Context context, List<T> data,OnAutoViewPagerItemClickListener listener) {
this.mContext = context;
this.data = data;
this.listener = listener;
}
public void init(AutoViewPager viewPager,BaseViewPagerAdapter adapter){
mView = viewPager;
mView.setAdapter(this);
mView.addOnPageChangeListener(this);
if (data == null || data.size() == 0){
return;
}
//设置初始为中间,这样一开始就能够往左滑动了
int position = Integer.MAX_VALUE/2 - (Integer.MAX_VALUE/2) % getRealCount();
mView.setCurrentItem(position);
if (!mView.isStart()) {
mView.start();
mView.updatePointView(getRealCount());
}
}
public void setListener(OnAutoViewPagerItemClickListener listener) {
this.listener = listener;
}
public void add(T t){
data.add(t);
notifyDataSetChanged();
mView.updatePointView(getRealCount());
}
public void add(List<T> list){
if (data == null) {
data = new ArrayList<>();
}
data.addAll(list);
notifyDataSetChanged();
mView.start();
mView.updatePointView(getRealCount());
}
public void init(List<T> list){
if (data == null) {
data = new ArrayList<>();
}
data.clear();
data.addAll(list);
notifyDataSetChanged();
if (!mView.isStart()) {
mView.start();
mView.updatePointView(getRealCount());
}
}
#Override
public int getCount() {
return (data == null || data.size() == 0 ) ? 0 : Integer.MAX_VALUE;
}
public int getRealCount(){
return data == null ? 0 : data.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView view = (ImageView) LayoutInflater.from(mContext)
.inflate(R.layout.imageview,container,false);
loadImage(view,position, data.get(position % getRealCount()));
container.addView(view);
//设置标题(不知道为什么标题跟图片对不上,所以做了如下处理,有大神看到帮忙看看。。。)
if (mView.getSubTitle() != null){
if (position == 0){
setSubTitle(mView.getSubTitle(),position,data.get((getRealCount() - 1)));
}else {
setSubTitle(mView.getSubTitle(),position,data.get((position - 1) % getRealCount()));
}
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemClick(position % getRealCount(),data.get(position % getRealCount()));
}
}
});
return view;
}
public abstract void loadImage(ImageView view,int position,T t);
public abstract void setSubTitle(TextView textView,int position,T t);
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mView.onPageSelected(position % getRealCount());
}
#Override
public void onPageScrollStateChanged(int state) {
}
public interface OnAutoViewPagerItemClickListener<T> {
void onItemClick(int position,T t);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeActivity();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}

CustomArrayAdapter.add() not changing my TextView

Java:
dateInserted = getDateFromDatePicker(datePicker);
calendarDateInserted.setTime(dateInserted);
finalDateShown = getStringRepresentationOfDate(calendarDateInserted.get(Calendar.DAY_OF_WEEK)) + " " + (calendarDateInserted.get(Calendar.MONTH) + 1) + "/" + (calendarDateInserted.get(Calendar.DATE)) + "/" + (calendarDateInserted.get(Calendar.YEAR));
Log.d("debug",finalDateShown); // Print the string to the LogCat
;
myArrayAdapter.add(new MyItem(finalDateShown));
MyArrayAdapter class:
private class MyArrayAdapter extends ArrayAdapter<MyItem> // My custom array adapter class
{
private int myResourceId = 0;
private LayoutInflater myLayoutInflater;
private RadioButton mySelectedRadioButton;
private int mSelectedPosition = -1;
private ButtonClickListener myClickListener = null;
public MyArrayAdapter(Context context, int myResourceId, List<MyItem> objects,ButtonClickListener myClickListener)
{
super(context, myResourceId, myItemList);
this.myResourceId = myResourceId;
myLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.myClickListener = myClickListener;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
final ViewHolder holder;
if (view == null)
{
view = myLayoutInflater.inflate(myResourceId, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) view.findViewById(R.id.dates_id);
holder.addDateButton = (Button) view.findViewById(R.id.add_date_button_id);
holder.addCommentButton = (Button)view.findViewById(R.id.add_comment_button_id);
holder.selectDateRadioButton = (RadioButton) view.findViewById(R.id.select_date_radio_button_id);
holder.addDateButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(position != mSelectedPosition && mySelectedRadioButton != null)
{
mySelectedRadioButton.setChecked(false);
}
mSelectedPosition = position;
mySelectedRadioButton = holder.selectDateRadioButton;
Log.d("debug", finalDateShown);
add(new MyItem(finalDateShown));
}
});
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
if(mSelectedPosition != position)
{
holder.selectDateRadioButton.setChecked(false);
}
else
{
holder.selectDateRadioButton.setChecked(true);
if(mySelectedRadioButton != null && holder.selectDateRadioButton != mySelectedRadioButton)
{
mySelectedRadioButton = holder.selectDateRadioButton;
}
}
return view;
} // End of getView() method
#Override
public void add(MyItem object)
{
super.add(object);
this.setNotifyOnChange(true);
}
private class ViewHolder
{
TextView dateTextView;
Button addDateButton;
Button addCommentButton;
RadioButton selectDateRadioButton;
}
}
Now the TextView is never changed to finalDateShown as it should be.
MyItem class:
class MyItem
{
public String date;
public boolean isRadioButtonChecked;
public MyItem(String date)
{
this.date = date;
this.isRadioButtonChecked = false;
}
}
listViewSingleRow:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/dates_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/date_text"
/>
<Button
android:id="#+id/add_comment_button_id"
android:layout_width="105sp"
android:layout_height="wrap_content"
android:text="#string/add_comment_button_text"
android:layout_toRightOf="#+id/add_date_button_id"
android:layout_toEndOf="#id/add_date_button_id"
/>
<Button
android:id="#+id/add_date_button_id"
android:layout_width="80sp"
android:layout_height="wrap_content"
android:text="#string/add_date_button_text"
android:layout_toRightOf="#id/dates_id"
android:layout_toEndOf="#id/dates_id"
/>
<RadioButton
android:id="#+id/select_date_radio_button_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/add_comment_button_id"
android:layout_toEndOf="#id/add_comment_button_id"
/>
</RelativeLayout>
Every time i use myArraAdapter.add(finalDateShown) its adding it with the android:Text="SomeText" i assigned in the XML instead of finalDateShown.
So whats wrong here?
EDIT:
Activity:
public class SexAcivity extends AppCompatActivity
{
ListView listView;
MyArrayAdapter myArrayAdapter;
List<MyItem> myItemList = new ArrayList<SexAcivity.MyItem>();
public interface ButtonClickListener
{
public abstract void onButtonClick(int position);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sex_acivity);
listView = (ListView) findViewById(R.id.list_view_id);
listView.setLayoutParams(layoutParams);
headerView = ((LayoutInflater)SexAcivity.this.getSystemService(SexAcivity.this.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_view_header, null, false);
listView.addHeaderView(headerView);
myArrayAdapter = new MyArrayAdapter(SexAcivity.this,R.layout.list_view_single_row,myItemList,new ButtonClickListener()
{
#Override
public void onButtonClick(int position)
{
}
});
listView.setAdapter(myArrayAdapter);
finalDateShown = getStringRepresentationOfDate(calendarDateInserted.get(Calendar.DAY_OF_WEEK)) + " " + (calendarDateInserted.get(Calendar.MONTH) + 1) + "/" + (calendarDateInserted.get(Calendar.DATE)) + "/" + (calendarDateInserted.get(Calendar.YEAR));
Log.d("debug",finalDateShown); // Print the string to the LogCat
myArrayAdapter.add(new MyItem(finalDateShown));
myArrayAdapter.setNotifyOnChange(true);
}
}
Thats basically it.
Option A: No need to call notifyDataSet or override of the add-method. Just set myAdapter.setNotifyOnChange(true) and it will do all the magic for add, insert, clear and remove. See here. The default value is true. So I wonder why your UI does not update automatically. The list of the adapter should be set in it's constructor and passed to the super-constructor. I see that you do this. And then the adapter should be set to the ListView by calling list.setAdapter.
Option B: First add the item, then call notifyDataSetChanged.
Just a side note: In terms of object oriented programming, you should move the call to notifyDataSetChanged into your implementation of the ArrayAdapter.
private class MyArrayAdapter extends ArrayAdapter<MyItem>
{
#Override
public void add(MyItem object)
{
// add
super.add(object);
// then notify UI
this.notifyDataSetChanged();
}
}

Unable to listen to setOnItemClickListener in ListView - Android

I have a ListView in my MainActivity which has a customAdapter to it. I am implementing a slider on each of the list items. I have also attached a footerView to my listView. Now my problem is that, the setOnClickListener is not fired, and I am not able to print the position's of the listView. It only print's for the footerView alone, which I have attached.
The code for MainActivity is
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
Then the code for my CustomAdapter is
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
Then finally the ViewPagerAdapter code is
public class MyViewPager extends ViewPager {
private static final String TAG = "MyViewPager";
private float xDown;
private float xMove;
private float yDown;
private float yMove;
private boolean isScroll = false;
private int selfIndex;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSelfIndex(int index) {
selfIndex = index;
}
public int getSelfIndex() {
return selfIndex;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.v(TAG, "on intercept");
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v(TAG, "on dispatch");
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.v(TAG, "action down: " + xDown + ", " + yDown);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
xMove = ev.getRawX();
yMove = ev.getRawY();
Log.v(TAG, "action move: " + xMove + ", " + yMove);
if (isScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
if (Math.abs(yMove - yDown) < 5 && Math.abs(xMove - xDown) > 20) {
isScroll = true;
} else {
return false;
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
isScroll = false;
}
return super.dispatchTouchEvent(ev);
}
}
The MainActivity layout is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
The layout for listview_item is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
Added all XML Layouts
listview_item_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:minHeight="100dp" >
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/main_list_text"
android:textSize="48sp"
android:textStyle="bold" />
<EditText
android:id="#+id/et_input_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_contact_hint"
android:textColorHint="#color/main_list_text"
android:textColor="#color/main_list_text"
android:textSize="30sp"
android:textStyle="bold"
android:inputType="textCapCharacters"
android:background="#null"
android:textCursorDrawable="#null"
android:singleLine="true"
android:imeOptions="actionDone"
android:visibility="gone" />
</RelativeLayout>
listview_item_slide
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_menu_cancel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:background="#color/gold"
android:gravity="center"
android:text="#string/cancel"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_delete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/green"
android:gravity="center"
android:text="#string/delete"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_block"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/royalblue"
android:gravity="center"
android:text="#string/block"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
</LinearLayout>
Please help me to listen to the onItemClickListener in the MainActivity's list. I am not able to figure out where I went wrong. Thanks in advance.
you have to put your "setOnItemClickListener" to your Adapter class insted of MainActivity.
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
ViewHolder holder;
View iView = convertView;
if (convertView == null) {
iView = inflater.inflate(R.layout.listview_item, parent, false);
holder = new ViewHolder();
holder.txt_name = (TextView) iView.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(
context.getAssets(), "KozGoPr6N-Regular.otf");
holder.txt_name.setTypeface(custom_fontG);
holder.txt_desc = (TextView) iView.findViewById(R.id.detail);
holder.ivProfile = (ImageView) iView.findViewById(R.id.flag);
iView.setTag(holder);
} else {
holder = (ViewHolder) iView.getTag();
}
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// Capture position and set results to the TextViews
holder.txt_name.setText(resultp.get(OurTeam.TAG_NAME));
holder.txt_desc.setText(resultp.get(OurTeam.TAG_DETAIL));
imageLoader.displayImage(TAG_IMAGEURL + resultp.get((OurTeam.TAG_IMG)),
holder.ivProfile, options);
// Capture ListView item click
iView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
// your code
}
});
return iView;
}
At a time you can handle click event either in Adapter class of in Activity. in your case you are doing both.
And to manage
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
Write above on click event of what ever is main view in listview_item layout (Do not forget to pass addContact and inputName views to your CustomAdapter).
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
/* mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});*/
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
and Adapter Class was..
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code here for list item click listener...
}
})
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
add this below line in your listview_item parent layout only.
android:descendantFocusability="blocksDescendants"
actually when the list item contains a element which can get focus then list item click listener not work.
Add this to the parent of your Listview and parent of your listview_item and try again:
android:descendantFocusability="blocksDescendants"
Like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
and this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:descendantFocusability="blocksDescendants"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
If this does not work, call isFocusable() on your EditText and TextView
addContact.isFocusable(false);
inputName.isFocusable(false);
I am guessing you made a common error. Please check/try both changes.
1) add android:descendantFocusability="blocksDescendants" into the ListView UI ("#+id/lv_main").
Note: If this and 2nd suggestion does not work, then the Listview layout may need rework.
2) mainListView.setItemsCanFocus(false);
Note: The Listview may be confused with focusing on an item in the UI.
I think the suggested code by "Nirmal Shethwala" looks good. It has the if/else block for if (convertView == null).
EDIT: I noticed you inflated 3 xml layout files in getView(). You can only have one, and that is listview_item in your code. I know this is not well documented. I have tried this in the past. The reason is getView() method has to return only one view, and your code return convertView; like me.
Sorry I know this will take some modifications in your layout.

Categories

Resources