How to display the actual image onclick from gridview - java

I'm trying to get the image in the chat box when I click on any of the images from the gridview however, whenever I try to do so it comes up with a text, so please advise what can be done to get the image itself instead of the text that is appearing, please help me out I've been stuck for too long
smiles_items_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:id="#+id/smile_image_view"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"/>
</LinearLayout>
BottomSheetDialog_Smiles.java
public class ImageAdapter2 extends BaseAdapter {
private Context mContext;
private final int[] mThumbIds;
String[] mThumbIdsString = null;
public ImageAdapter2(Context c, int[] mThumbIds , String[] mThumbIdsString)
{
mContext = c;
this.mThumbIds = mThumbIds;
this.mThumbIdsString = mThumbIdsString;
}
#Override
public int getCount() {
return mThumbIds.length & mThumbIdsString.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
ImageView img;
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
final Holder holder = new Holder();
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.smiles_items_layout, null);
null);
holder.img = (ImageView) grid.findViewById(R.id.smile_image_view);
holder.img.setImageResource(mThumbIds[position]);
gridView2.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
Drawable drawable;
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int i, long l) {
JSONDictionary imageChat = new JSONDictionary();
LinearLayout layout= (LinearLayout)view;
ImageView imageView = (ImageView) layout.getChildAt(0);
imageView.getDrawable();
imageChat.put("message", imageView);
Communicator.getInstance().emit("new chat message",
imageChat);
}
});
return grid;
}
}
This is the result which appears when clicking on the image

Do you need an ImageView inside an image?
I used this code to get an image.
Send your view this method get as image.
protected Bitmap ConvertToBitmap(ImageView image_view) {
Bitmap map;
image_view.setDrawingCacheEnabled(true);
image_view.buildDrawingCache();
return map=image_view.getDrawingCache();
}
In ur adapter code
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = ConvertToBitmap(holder.img);;
//now get bitmap used to assign
imageChat.put("message", b);
Communicator.getInstance().emit("new chat message",
imageChat);
}
});

Related

android.support.v7.widget.AppCompatImageView cannot be cast to android.view.ViewGroup

I'm taking pictures by camera, adding them to ArrayList as Bitmap. I have recyclerView that is showing taken images. I want to have an alertdialog, that shows clicked image with option to delete. I'm having a problem with setting custom layout to AlertDialog. When I click on image, app crashes and error says
java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView cannot be cast to android.view.ViewGroup
Error point to this row of code
View viewInflated = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_image, (ViewGroup) view,false);
imageDialog.setView(viewInflated);
but I'm not sure what I should do. I tried to change (ViewGroup) to something else but with no luck.
Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Bitmap> fotky;
private Bitmap foto;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_view_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
foto = fotky.get(position);
holder.photo.setImageBitmap(foto);
holder.photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder imageDialog = new AlertDialog.Builder(view.getContext());
imageDialog.setTitle("Image");
View viewInflated = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_image, (ViewGroup) view,false);
imageDialog.setView(viewInflated);
ImageView image = viewInflated.findViewById(R.id.fotka);
image.setImageBitmap(foto);
imageDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
imageDialog.setNegativeButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
remove(position);
}
});
imageDialog.show();
//TODO tady ukázat full image s možností smazání
//remove(position);
}
});
}
public void add(int position, Bitmap item) {
fotky.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
fotky.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, fotky.size());
}
public Adapter(List<Bitmap> myDataset) {
fotky = myDataset;
}
#Override
public int getItemCount() {
return fotky.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView photo;
public ViewHolder(View itemView) {
super(itemView);
photo = itemView.findViewById(R.id.imageView);
}
}
}
Dialog_image.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fotka"
android:contentDescription="photo"/>
</LinearLayout>
Reason behind this crash is you have setup click listener on holder.photo which is of type AppCompatImageView. inside onClick block you are typecasting it to ViewGroup.
Change it to following.
View viewInflated = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_image, null);
It should work.

Converting an Integer to a Drawable

I have two Adapter classes and in the first one, i have an Array of Integers[] named mThumbIds which is initialized like this :
// References to our images
private Integer[] mThumbIds = {
R.mipmap.beyondthe_ferocious_flash_majin_vegeta_icon,
R.mipmap.full_tilt_kamehameha_super_saiyan2_gohan_youth_icon,
R.mipmap.merciless_condemnation_goku_black_super_saiyan_rose_and_zamasu_icon,
R.mipmap.everlasting_legend_super_saiyan_goku_icon,
R.mipmap.indestructible_saiyan_evil_legendary_super_saiyan_broly_icon
};
I want to extract an Integer from this array(let's say mThumbIds[0]) and then pass it into my other adapter class and use it to get a valid drawable that i can use for my imageViews.
This is the 2nd adapter's List to hold the extracted Integer:
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
And here is where i need the drawable :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mGLBIcons.get(position));
return imageView;
}
So far, nothing that i've tried has worked so i am asking for your help!
EDITED
ImageViewAdapterClass:
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
public UserBoxGlbImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Drawable drbl = mContext.getResources().getDrawable(mGLBIcons.get(0));
imageView.setImageDrawable(drbl);
return imageView;
}
public void passInteger(Integer integer) {
mGLBIcons.add(integer);
}
}
GridSettingFragmentClass:
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext()));
return view;
}
}
fragment_user_box_glb.xml :
<LinearLayout 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/colorSecondaryGLB"
android:orientation="vertical"
tools:context="com.dcv.spdesigns.dokkancards.ui.UserBoxGLBFragment">
<GridView
android:id="#+id/userBoxGlbGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
</LinearLayout>
you are using mipmap id and you are trying to load it as a drawable, i doubt it will work. try putting the images in the drawable folder and use thr drawable id.
this is how you set a drawable image in a adapter:
imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_success))
in your case it would be
imageView.setImageDrawable(context.getResources().getDrawable(listOfImages[position]))
Change your constructoras:
public UserBoxGlbImageAdapter(Context c, List<Integer> iconsList) {
mContext = c;
mGLBIcons = iconsList;
}
try using as below:
image_view_layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image_view"
android:layout_width="225dp"
android:layout_height="225dp" />
</LinearLayout>
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
List<Integer> listOfimages = new ArrayList<>();
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
listOfimages.add(R.drawable.beyondthe_ferocious_flash_majin_vegeta_icon);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext(),listOfimages));
return view;
}
}
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
public UserBoxGlbImageAdapter(Context c,List<Integer> listOfIcons) {
mContext = c;
mGLBIcons = listOfIcons;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If it's not recycled, initialize some attributes
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_view_layout, parent, false));
}
ImageView imageView = (ImageView)convertView.findViewById(R.id.image_view)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8); imageView.setImageDrawable(mContext.getResources().getDrawable(mGLBIcons.get(0)));
return imageView;
}
}

Image in Cardview OnClickListener

How do i insert a "onclicklistener" on the imageviews in a cardview?
Context: I extracted frames from a video using ffmpeg, and have images displayed in a cardview, now i need to set a onclicklistener to get the bitmap of the image I clicked.
If i simply applied onClickListener to the view, like so:
view.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// item clicked
}
});
Will it give me the correct image bitmap that i clicked?
I currently display images in a cardview using an adapter:
Activity
public class PreviewImageActivity extends AppCompatActivity {
private static final String FILEPATH = "filepath";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
TextView tvInstruction=(TextView)findViewById(R.id.tvInstruction) ;
GridLayoutManager lLayoutlLayout = new GridLayoutManager(PreviewImageActivity.this, 4);
RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayoutlLayout);
String filePath = getIntent().getStringExtra(FILEPATH);
ArrayList<String> f = new ArrayList<String>();
File dir = new File(filePath);
tvInstruction.setText("Images stored at path "+filePath);
File[] listFile;
listFile = dir.listFiles();
for(File e:listFile)
{
f.add(e.getAbsolutePath());
}
PreviewImageAdapter rcAdapter = new PreviewImageAdapter( f);
rView.setAdapter(rcAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
}
Adapter
public class PreviewImageAdapter extends RecyclerView.Adapter<PreviewImageAdapter.MyViewHolder> {
private ArrayList<String> paths;
public PreviewImageAdapter( ArrayList<String> paths) {
this.paths = paths;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_gallery, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bitmap bmp = BitmapFactory.decodeFile(paths.get(position));
holder.ivPhoto.setImageBitmap(bmp);
}
#Override
public int getItemCount() {
return paths.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView ivPhoto;
public MyViewHolder(View itemView) {
super(itemView);
ivPhoto = (ImageView) itemView.findViewById(R.id.ivPhoto);
}
}
}
XML
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="#dimen/dp4"
android:layout_margin="#dimen/dp8">
<ImageView
android:id="#+id/ivPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
/>
</android.support.v7.widget.CardView>
You should add the OnClickListener in the PreviewImageAdapter onBindViewHolder method, where you have access to the imageview.
holder.ivPhoto.setOnClickListener(new View.OnClickListener())...
another workaround is to implement onClickListener on your ViewHolder class and then switch/case the view ids for different actions like:
class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
...
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.v1:
// Your code
break;
case R.id.v2:
// Your Code
break;
}
}
}

Android Studio Dynamically Changing Images in GridView

I have set up a GridView Successfully, however I want to be able to change the Images within the the GridView dependent upon a variable. For example:
int a = 2
if (a == 2){
Integer[] images = {
R.drawable.image1
R.drawable.image3
}
} else {
Integer[] images = (
R.drawable.image2
R.drawable.image4
}
}
However I can't find a way to do this. The code I am working with at the moment is:
GridView cardList = (GridView) findViewById(R.id.cardList);
cardList.setAdapter(new ImageAdapter(this));
cardList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(Create.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(215, 215));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(images[position]);
return imageView;
}
private Integer[] images = {
R.drawable.iamge1, R.drawable.image2
};
}
Try something like this:
The activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.gridView);
int images[] = {R.drawable.ic_action_name};
ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext(),images);
gridView.setAdapter(imageAdapter);
}
}
Your adapter class:
public class ImageAdapter extends BaseAdapter {
private int images[];
Context context;
public ImageAdapter(Context context, int images[]){
this.context = context;
this.images = images;
}
private class Holder{
ImageView imageView;
}
#Override
public int getCount(){
return images.length;
}
#Override public Object getItem(int position){
return null;
}
#Override
public long getItemId(int position){
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent){
//All of this Holder stuff is so that the View doesn't jump around wildly
final Holder holder;
LayoutInflater inflater;
if (view == null){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.singleimage,null);
holder = new Holder();
holder.imageView = (ImageView) view.findViewById(R.id.singleImage);
view.setTag(holder);
}
else {
holder = (Holder) view.getTag();}
holder.imageView.setImageResource(images[position]);
return view;
}
}
You also need a simple xml file for the single image in the gridView. Name this "singleimage.xml"
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/singleImage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
Activity xml file:
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ri.emily.testapp.MainActivity">
<GridView
android:layout_width="match_parent"
android:id="#+id/gridView"
android:layout_height="match_parent" />
</RelativeLayout>

Listview selects mutliple items when clicked

I'm trying to make a task manager, and I only have one problem. I have a listview that gets inflated. All the elements in the listview are correct. The problem is that when I select an item, the listview will select another item away. I've heard listviews repopulate the list as it scrolls down to save memory. I think this may be some sort of problem. Here is a picture of the problem.
If i had more apps loaded, then it would continue to select multiple at once.
Here is the code of my adapter and activity and XML associated
public class TaskAdapter extends BaseAdapter{
private Context mContext;
private List<TaskInfo> mListAppInfo;
private PackageManager mPack;
public TaskAdapter(Context c, List<TaskInfo> list, PackageManager pack) {
mContext = c;
mListAppInfo = list;
mPack = pack;
}
#Override
public int getCount() {
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
}
});
return convertView;
public class TaskManager extends Activity implements Runnable
{
private ProgressDialog pd;
private TextView ram;
private String s;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskpage);
setTitleColor(Color.YELLOW);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run()
{
//System.out.println("In Taskmanager Run() Thread");
final PackageManager pm = getPackageManager();
final ListView box = (ListView) findViewById(R.id.cBoxSpace);
final List<TaskInfo> CK = populate(box, pm);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
ram.setText(s);
box.setAdapter(new TaskAdapter(TaskManager.this, CK, pm));
//System.out.println("In Taskmanager runnable Run()");
endChecked(CK);
}
});
handler.sendEmptyMessage(0);
}
Taskinfo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/tmImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:scaleType="centerCrop"
android:adjustViewBounds="false"
android:focusable="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tmbox"
android:lines="2"/>
</LinearLayout>
Taskpage.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:orientation="vertical">
<ListView
android:id="#+id/cBoxSpace"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/RAM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
<Button
android:id="#+id/endButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="End Selected Tasks" />
</LinearLayout>
Any ideas for what reason mutliple items are selected with a single click would be GREATLY appreciated. I've been messing around with different implementations and listeners and listadapters but to no avail.
I think the point is you only save checking state in the view(v.setSelected).
And you reuse these view, so its checkbox is always not change its state.
You can create a state array to save every checking state of every TaskInfo, and check this array when you create a view.
for example
// default is false
ArrayList<Boolean> checkingStates = new ArrayList<Boolean>(mListAppInfo.size());
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(checkingStates.get(position));
convertView.setSelected(checkingStates.get(position));
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
checkingStates.get(position) = false;
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
checkingStates.get(position) = true;
}
}
});
return convertView;
}
I'm not 100% sure what you are trying to do, but part of your problem might be related to the condition in your onClick method:
if(v.isSelected())
I think you want that to read
if(v.isChecked())
isSelected is inherited from View, and it means something different from isChecked
Also, the whether the CheckBox is checked or not is independent from your data model since it is a recycled view. Your CheckBox should be checked based on entry (I'm assuming your TextInfo class has an isChecked() method that returns a boolean:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(entry.isChecked());
}
I don't think you need the View.OnClickListener you are attaching to convertView. You should handle that in the OnItemClickListener attached to the ListView. Assuming your ListView is called listView and TaskInfo instances have setChecked and isChecked methods:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
entry = mListAppInfo.get(position);
entry.setChecked(!entry.isChecked());
}
});
First of all don't set the list checked or unchecked on view position.
because view position means only visible items position in your listview but you would like to set checked or uncheked status on a particular list item.
That's why this problem arises in your code.
You have the need to set the items checked and unchecked on your custom arraylist getter setter like the code i have attached below:
package com.app.adapter;
public class CategoryDynamicAdapter {
public static ArrayList<CategoryBean> categoryList = new ArrayList<CategoryBean>();
Context context;
Typeface typeface;
public static String videoUrl = "" ;
Handler handler;
Runnable runnable;
// constructor
public CategoryDynamicAdapter(Activity a, Context context, Bitmap [] imagelist,ArrayList<CategoryBean> list) {
this.context = context;
this.categoryList = list;
this.a = a;
}
// Baseadapter to the set the data response from web service into listview.
public BaseAdapter mEventAdapter = new BaseAdapter() {
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return categoryList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView title,category,uploadedBy;
ImageView image;
RatingBar video_rating;
Button report_video ,Flag_video;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder vh = null ;
if(convertView == null) {
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate (R .layout.custom_category_list_layout,null,false);
vh.title = (TextView) convertView .findViewById (R.id.title);
vh.image = (ImageView) convertView.findViewById(R.id.Imagefield);
convertView.setTag(vh);
}
else
{
vh=(ViewHolder) convertView.getTag();
}
try
{
final CategoryBean Cb = categoryList.get(position);
//pay attention to code below this line i have shown here how to select a listview using arraylist getter setter objects
String checkedStatus = Cb.getCheckedStringStaus();
if(checkdStatus.equal("0")
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else ////checkdStatus.equal("1")
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
catch (Exception e)
{
e.printStackTrace();
}

Categories

Resources