ListView set visible two buttons on long click - android

I have problem with ListView and ArrayAdapter. I want to show delete button on long press on ListView item. Problem is that I get more than once button showed on long click (depends of how many item i see on display. If I'm in portrait mode, I see, for example first 10 of 15, and when I press long on item at position 3, i will see two buttons, at position 3 and at position 13. If I'm at landscape mode, I see first 4 of 15 items, and when I press long at 2, I will see buttons at position 2, 6, 10, 14.). But, when I press other buttons, I still delete original item (item that long pressed). Here is example of my code.
TicketListAdapter
public class TicketListAdapter extends ArrayAdapter<Ticket> {
Context context;
int layoutResourceId;
TabFragmentAdapter tabMenager;
List<Ticket> data = null;
public TicketListAdapter(Context context, int layoutResourceId, List<Ticket> objects, TabFragmentAdapter tabMenager) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = objects;
this.tabMenager = tabMenager;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
TicketHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new TicketHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.item_icon);
holder.txtTitle = (TextView) row.findViewById(R.id.name);
holder.txtGain = (TextView) row.findViewById(R.id.description);
holder.btnDelete = (Button) row.findViewById(R.id.deleteTicketButton);
holder.btnDelete.setOnClickListener(new DeleteTicketAction((Activity) context, getItemId(position), tabMenager, null, null));
row.setTag(holder);
} else {
holder = (TicketHolder) row.getTag();
}
Ticket ticket = data.get(position);
holder.txtTitle.setText(ticket.ticketName);
holder.txtGain.setText("Possible gain: " + ticket.possibleGain);
holder.imgIcon.setImageResource(StatusHelper.getStatusIconType(ticket.status.status, context));
return row;
}
static class TicketHolder {
ImageView imgIcon;
TextView txtTitle;
TextView txtGain;
Button btnDelete;
}
#Override
public long getItemId(int position) {
return data.get(position).getId();
}
list_ticket_view.xml
<?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" >
<ImageView
android:id="#+id/item_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:contentDescription="#null"
android:src="#drawable/checkbox_marked_circle"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="5dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center_vertical"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/item_icon"
android:layout_toEndOf="#+id/item_icon"
android:paddingLeft="5dp"
android:paddingTop="5dp"/>
<TextView android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:layout_toRightOf="#+id/item_icon"
android:layout_toEndOf="#+id/item_icon"
android:paddingLeft="5dp"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/deleteTicketButton"
android:focusable="false"
android:visibility="gone"
android:layout_marginTop="5dp"
android:background="#drawable/delete_forever"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
ListFragment
public class AllTicketsFragment extends ListFragment implements OnItemClickListener,
AdapterView.OnItemLongClickListener, FragmentUpdateInterface {
TicketListAdapter arrayAdapter;
TabFragmentAdapter tabMenager;
public AllTicketsFragment() {
// Required empty public constructor
}
public AllTicketsFragment(TabFragmentAdapter tabManager) {
this.tabMenager = tabManager;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list_view, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
List<Ticket> tickets = null;
try {
tickets = new GetTicketFromDBTask(getActivity()).execute("all").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
arrayAdapter = new TicketListAdapter(getActivity(), R.layout.list_ticket_view, tickets, tabMenager);
setListAdapter(arrayAdapter);
getListView().addFooterView(getLayoutInflater(savedInstanceState).inflate(R.layout.list_footer_view, null), null, false);
getListView().setOnItemClickListener(this);
getListView().setOnItemLongClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), TicketDetailActivity.class);
intent.putExtra("id", id);
startActivityForResult(intent, 1000);
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Button deleteButton = (Button) view.findViewById(R.id.deleteTicketButton);
if (deleteButton.getVisibility() == View.VISIBLE) {
deleteButton.setVisibility(View.GONE);
} else {
deleteButton.setVisibility(View.VISIBLE);
}
arrayAdapter.notifyDataSetChanged();
return true;
}
}

Related

How to hold the selected image in GridView and pass to next activity after I click Button

In my Activity I have an EditText, a Button and a GridView. The user selects the image from the GridView and enters the name in the EditText, and then clicks the done button.
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/l1"
>
<View
android:layout_width="#dimen/btm_sht_line"
android:layout_height="#dimen/btm_sht_height"
android:layout_marginTop="#dimen/btm_top"
android:layout_gravity="center_horizontal"
android:background="#color/colorPrimaryDark"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/header_create_a_new_list"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textStyle="bold"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/l2"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/marin_top"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listname"
android:hint="#string/list_title_name"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="#dimen/marin_top"
android:layout_marginStart="#dimen/marin_top"
android:inputType="text"
android:autofillHints="#string/list_title_name" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/done"
android:src="#drawable/ic_check_circle"
android:layout_marginRight="15dp"
android:layout_marginEnd="#dimen/marin_top"
android:layout_marginLeft="#dimen/margin_left"
android:layout_marginStart="#dimen/margin_left"
tools:ignore="ContentDescription"
/> </LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/l3"
android:orientation="vertical"
>
<View style="#style/Divider"
android:layout_marginTop="#dimen/marin_top"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/r1"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scroll"
><GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridview"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</ScrollView>
</RelativeLayout>
</LinearLayout>
I want to move the selected image and the entered text to another Activity
<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=".CheckslateHome">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:id="#+id/ima"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/getlistname"
android:text="hi welcome"
android:layout_below="#+id/ima"
/>
</RelativeLayout>
In my code when the user selects the image, before entering the name, it loads to a new empty window. Also I have 6 images in my drawable Folder and only 3 images are being displayed in the GridView.
Java class
public class NewListCreate extends BottomSheetDialogFragment {
Integer[] images={R.drawable.menu,R.drawable.musicbox,R.drawable.shoppingbag,R.drawable.shoppingcart,R.drawable.wallet,R.drawable.weddingdress};
GridView gridView;
ArrayList<imageModel> arrayList;
public NewListCreate() {}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.new_list_create, container, false);
ImageButton done = view.findViewById(R.id.done);
final EditText listname = (EditText) view.findViewById(R.id.listname);
final GridView gridView = (GridView) view.findViewById(R.id.gridview);
arrayList = new ArrayList<imageModel>();
for (int i = 0; i < images.length; i++) {
imageModel imagemodel = new imageModel();
imagemodel.setmThumbIds(images[i]);
//add in array list
arrayList.add(imagemodel);
}
final ImageAdapterGridView adapterGridView = new ImageAdapterGridView(getContext(), arrayList);
gridView.setAdapter(adapterGridView);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
adapterGridView.setSelectedPosition(i);
adapterGridView.notifyDataSetChanged();
int imageRes = images[i];
Intent intent = new Intent(getContext(),CheckslateHome.class);
intent.putExtra("IMAGE_RES", imageRes);
startActivity(intent);
}
});
return view;
}
}
AdapterClass
public class ImageAdapterGridView extends BaseAdapter {
private int selectedPosition = -1;
Context context;
ArrayList<imageModel> arrayList;
public ImageAdapterGridView(Context context, ArrayList<imageModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return arrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view==null)
{
view = LayoutInflater.from(context).inflate(R.layout.image_list, viewGroup, false);
}
ImageView imageView;
imageView = (ImageView) view.findViewById(R.id.image);
imageView.setImageResource(arrayList.get(i).getmThumbIds());
if (i == selectedPosition) {
view.setBackgroundColor(Color.WHITE);
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
return view;
}
public void setSelectedPosition(int position) {
selectedPosition = position;
}
}
what i was Looking was Something Like this
[![enter image description here][1]][1]
Copy and paste this hope it solve ur Problem
public class NewListCreate extends BottomSheetDialogFragment {
int[] images={R.drawable.menu,R.drawable.musicbox,R.drawable.shoppingbag,R.drawable.shoppingcart,R.drawable.wallet,R.drawable.weddingdress};
int imageRes = images[0];
public NewListCreate() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_list_create, container, false);
ImageButton done = view.findViewById(R.id.done);
final EditText listname = (EditText) view.findViewById(R.id.listname);
final GridView gridView = (GridView) view.findViewById(R.id.gridview);
final CustomAdpter customAdpter = new CustomAdpter(images,getContext());
gridView.setAdapter(customAdpter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
customAdpter.selectedImage = i;
customAdpter.notifyDataSetChanged();
imageRes = images[i];
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemname = listname.getText().toString();
if (!TextUtils.isEmpty(listname.getText().toString())) {
startActivity(new Intent(getContext(), CheckslateHome.class).putExtra("data", itemname).putExtra("image",imageRes));
dismiss();
} else {
Toast.makeText(getContext(), "List Name not Empty ", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
public class CustomAdpter extends BaseAdapter{
private int[] icons;
private Context context;
private LayoutInflater layoutInflater;
public int selectedImage = 0;
public CustomAdpter(int[] icons, Context context) {
this.icons = icons;
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null)
{
view = layoutInflater .inflate(R.layout.image_list,viewGroup,false);
}
ImageView imageicons = view.findViewById(R.id.image);
if (i < icons.length) {
imageicons.setImageResource(icons[i]);
if (i != selectedImage) {
imageicons.setImageAlpha(50);
}
imageicons.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageicons.setLayoutParams(new GridView.LayoutParams(150, 150));
if (i == selectedImage) {
view.setBackgroundColor(Color.WHITE);
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
};
return view;
}
}
I think what you're looking for is passing data through navigation.
It will allow you send your image and name data from one activity/fragment to the next one.
Check out data-binding as well, might be useful.

ListView OnItemClickListener not working within a fragment

I have reviewed the many questions about this issue, but I still haven't found a solution that works for me. I must be missing something along the way.
My MainActivity handles my Fragments. The default Fragment contains a ListView displaying nearby WIFI access points.
As with other similar questions, I don't get any response when I click on items in the ListView.
Here is my list item layout:
<?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="wrap_content"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="#+id/wifi_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_action_wifi"
android:tint="#color/ws_green" />
<TextView
android:id="#+id/device_id"
android:layout_width="fill_parent"
android:layout_height="24dp"
android:layout_toRightOf="#+id/wifi_icon"
android:layout_toEndOf="#+id/wifi_icon"
android:textAlignment="center"
android:gravity="bottom"
android:text="00:00:00:00:00:00"
android:textColor="#color/ws_blue"
android:textStyle="bold"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/wifi_power"
android:layout_width="fill_parent"
android:layout_height="24dp"
android:textAlignment="center"
android:gravity="top"
android:text="Power goes here"
android:textColor="#color/ws_blue"
android:layout_marginLeft="#dimen/text_margin"
android:layout_marginRight="#dimen/text_margin"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/wifi_icon" />
</RelativeLayout>
My list item class:
public class WifiItem extends RelativeLayout {
WifiItem rootView;
TextView lblPrimary;
TextView lblSecondary;
ImageView icon;
public WifiItem(Context context) {
super(context);
init(context);
}
public WifiItem(Context context, AttributeSet attributeSet){
super(context, attributeSet);
init(context);
}
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rootView = (WifiItem) inflater.inflate(R.layout.item_wifi, this);
lblPrimary = (TextView) rootView.findViewById(R.id.device_id);
lblSecondary = (TextView) rootView.findViewById(R.id.wifi_power);
icon = (ImageView) rootView.findViewById(R.id.wifi_icon);
}
public void setTvPrimaryText(String text){
lblPrimary.setText(text);
}
public void setTvSecondaryText(String text){
lblSecondary.setText(text);
}
}
And the onCreateView() method of the Fragment that contains the Listview:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_wifi_list, container, false);
Context context = view.getContext();
RelativeLayout relativeLayout = (RelativeLayout) view;
ListView listView = (ListView) relativeLayout.findViewById(R.id.lst_wifi_items);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.i("WIFI_FRAGMENT_ONCLICK", "ITEM SELECTED: " + i);
mListener.onListFragmentInteraction(view);
}
});
listView.setAdapter(new WifiItemListAdapter(getContext(), new ArrayList<ScanResult>()));
return view;
}
Any suggestions would be greatly appreciated.
EDIT:
My WifiListAdapter:
public class WifiItemListAdapter extends BaseAdapter {
protected List<ScanResult> scanResults;
public LayoutInflater inflater;
public WifiItemListAdapter(Context context, List<ScanResult> scanResult){
super();
this.scanResults = scanResult;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getCount() {
return scanResults.size();
}
#Override
public Object getItem(int i) {
return scanResults.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_wifi, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.wifi_icon);
holder.tvPrimary = (TextView) convertView.findViewById(R.id.device_id);
holder.tvSecondary = (TextView) convertView.findViewById(R.id.wifi_power);
holder.imageView.setImageResource(R.drawable.ic_wifi_black_24dp);
holder.tvPrimary.setText(scanResults.get(position).SSID);
holder.tvSecondary.setText("RSSI: " + scanResults.get(position).level + " dBm");
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
holder.tvPrimary.setText(scanResults.get(position).SSID);
holder.tvSecondary.setText("Power: " + scanResults.get(position).level + " dBm");
}
return convertView;
}
public static class ViewHolder{
ImageView imageView;
TextView tvPrimary;
TextView tvSecondary;
}
}
The issue is here:
`listView.setOnItemClickListener(new ListView.OnItemClickListener() `
You need to use new AdapterView.OnItemClickListener() instead.
So it would be something like this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("WIFI_FRAGMENT_ONCLICK", "ITEM SELECTED: " + i);
mListener.onListFragmentInteraction(view);
}
});
Hope it helps
The error was in my BroadcastReceiver.
After scanning for WIFI networks I did this:
listView = new ListView(context);
container.addView(listView);
When I should have been doing this:
listView = (ListView) container.findViewById(android.R.id.list);
It seems I was creating and displaying a new ListView on top of the old one, but the new one didn't have any Listeners attached to it.

Android : ListFragment loading continuously

I am extending my class to ListFragment. Below I posted the relative.
My issue is, I didn't get any error in runtime, but in Output it still loading the page.
Output:
Administration.java:
public class Administration extends ListFragment {
int[] img = { R.drawable.project, R.drawable.user, R.drawable.group,
R.drawable.roles, R.drawable.news, R.drawable.document };
private String item[] = { "Project", "Users", "Group",
"Roles and Permission", "News", "Documents" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setDividerHeight(2);
getListView().setAdapter(new BindDataAdapter(getActivity(), img, item));
}
#SuppressWarnings("deprecation")
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
for (int a = 0; a < l.getChildCount(); a++) {
l.getChildAt(a).setBackgroundColor(Color.TRANSPARENT);
}
}
}
I didn't use any layout in listFragment.I use the layout in BindDataAdapter.java
BindDataAdapter.java:
public class BindDataAdapter extends BaseAdapter {
Activity mLocal;
int[] imgArray;
String titleA[];
LayoutInflater mLayoutInflater;
public BindDataAdapter(Activity administration, int[] imageArray, String[] title) {
mLocal = administration;
imgArray = imageArray;
titleA = title;
mLayoutInflater = (LayoutInflater) administration
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return imgArray.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
private class Holder {
ImageView image;
TextView textView;
}
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.activity_list, null);
holder = new Holder();
holder.image = (ImageView) convertView.findViewById(R.id.iamge);
holder.textView = (TextView) convertView.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.image.setBackgroundResource(imgArray[position]);
holder.textView.setText(titleA[position]);
return convertView;
}
}
activity_list.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/whitelist"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/iamge"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="4dp"
android:contentDescription="#string/app_name" >
</ImageView>
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20dp"
android:padding="#dimen/padding_medium"
android:paddingLeft="10dp"
android:text="#string/hello_world"
android:textColor="#android:color/black"
android:textStyle="bold"
/>
</LinearLayout>
I didn't know why it has been loading continuously. Any help is mostly appreciated.Thank you.
Probably showing progress-bar is default in-built progress for ListFragment. So use setListShown to dismiss built-in indeterminant progress-bar after setting adapter for ListView as:
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
.....
setListShown(true);
}

Changing background color of list items in custom list view

I used the following code create a custom listview ....But the problem with this code it it is selecting only one item..but highlighting many items...i mean ..for example..if i have 8 items in the list..And i can see only 3 items(rest i have to scroll to see)..if i click the first item...it gets highlighted along with the fourth and the 7th item...
public class MainMenu extends Activity {
ListView lmenu;
View v1;
String s;
Class<?> ourclass;
View layout, row;
static int trantype;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menulist);
Menu Menu_data[] = new Menu[] { new Menu("1.White"),
new Menu("2.Blue"), new Menu("3.Purple"), new Menu("4.Red"),
new Menu("5.Yellow"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black") };
MenuAdapter adapter = new MenuAdapter(this, R.layout.menutext,
Menu_data);
lmenu = (ListView) findViewById(R.id.mainmenu);
lmenu.setAdapter(adapter);
lmenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> ada, View v, int position,
long id) {
// TODO Auto-generated method stub
/*
* v.setBackgroundColor(Color.parseColor("#FCD5B5")); if (!(v1
* == null) && v1 != v)
* v1.setBackgroundColor(Color.parseColor("#EEEEEE")); v1 = v;
*/
Intent swipeit = new Intent(getBaseContext(), Swipeit.class);
trantype = position + 1;
startActivity(swipeit);
}
});
findViewById(R.id.BLogout).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
public class Menu {
public String title;
public Menu() {
super();
}
public Menu(String title) {
super();
this.title = title;
}
}
public class MenuAdapter extends ArrayAdapter<Menu> {
Context context;
int layoutResourceId;
Menu data[] = null;
LayoutInflater inflater;
boolean[] arrBgcolor;
private int activeHex, inactiveHex;
public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
activeHex = Color.parseColor("#FCD5B5");
inactiveHex = Color.parseColor("#EEEEEE");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arrBgcolor = new boolean[13];
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
try {
MenuHolder holder = null;
row = convertView;
// convertView.setBackgroundColor(Color.BLACK);
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MenuHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tv1);
row.setTag(holder);
} else {
holder = (MenuHolder) row.getTag();
}
Menu Menu = data[position];
holder.txtTitle.setText(Menu.title);
holder.txtTitle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
resetArrbg();
arrBgcolor[position] = true;
if (arrBgcolor[position]) {
row.setBackgroundColor(activeHex);
} else {
row.setBackgroundColor(inactiveHex);
}
notifyDataSetChanged();
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_LONG).show();
}
return row;
}
private void resetArrbg() {
for (int i = 0; i < arrBgcolor.length; i++) {
arrBgcolor[i] = false;
}
}
public class MenuHolder {
TextView txtTitle;
}
}
}
my xml containing list...
<include
android:id="#+id/header"
android:layout_alignParentTop="true"
layout="#layout/header" />
<RelativeLayout
android:id="#+id/Rlmain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header"
android:orientation="vertical" >
<TextView
android:id="#+id/TMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="8dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="8dp"
android:text="Main Menu"
android:textColor="#000000"
android:textSize="15dp" />
<View
android:id="#+id/Vtop"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_below="#+id/TMain"
android:background="#android:color/darker_gray" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/Vbot"
android:layout_below="#+id/Rlmain"
android:orientation="vertical" >
<ListView
android:id="#+id/mainmenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#E0E0E0"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:dividerHeight="20dp" >
</ListView>
</RelativeLayout>
<View
android:id="#+id/Vbot"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_above="#+id/textView1"
android:background="#android:color/darker_gray" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="© India Transact Services Ltd."
android:textColor="#000000"
android:textSize="15dp" />
</RelativeLayout>
my xml for list....
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LLtv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EEEEEE"
android:cacheColorHint="#00000000" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:textColor="#000000"
android:textSize="20dp" />
</LinearLayout>
Can please anyone help me and tell where i am going wrong?
What you want can't be achieved with your current setup. You need to implement a custom adapter where you have access to the getView() method. For reasons made clearer in the answer here, what you need to do is use some sort of data-container that will hold the status of an individual row using some indicator and then perform your action based on it's position on the container (which should correspond to its position on the listview)
for example, check out this re-write:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
resetArrbg();
arrBgcolor[position] = true;
if (arrBgcolor[position]) {
v.setBackgroundColor(Color.parseColor("#FCD5B5"));
} else {
v.setBackgroundColor(Color.BLUE);
}
}
boolean[] arrBgcolor = new boolean[list.size()];
private void resetArrbg() {
for (int i = 0; i < arrBgcolor.length; i++) {
arrBgcolor[i] = false;
}
}
Does it make sense now why it can't work with the current set-up? The else part of the method, the part affecting the other views, can never take place because you don't have access to the other positions in the onListItemClick method, but you do in getView(). This is of course, unless you know of a way around this then, by all means, more power to you. all the same i don't think the v1 technique do you any good.
EDIT:
public class MainActivity extends Activity {
ListView lmenu;
View v1;
String s;
Class<?> ourclass;
View layout, row;
static int trantype;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menulist);
Menu Menu_data[] = new Menu[] { new Menu("1.White"),
new Menu("2.Blue"), new Menu("3.Purple"), new Menu("4.Red"),
new Menu("5.Yellow"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black") };
MenuAdapter adapter = new MenuAdapter(this, R.layout.menutext, Menu_data);
lmenu = (ListView) findViewById(R.id.mainmenu);
lmenu.setAdapter(adapter);
}
public class Menu {
public String title;
public Menu() {
super();
}
public Menu(String title) {
super();
this.title = title;
}
}
public class MenuAdapter extends ArrayAdapter<Menu> {
Context context;
int layoutResourceId;
Menu data[];
LayoutInflater inflater;
boolean[] arrBgcolor;
private int activeHex, inactiveHex;
public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
activeHex = Color.parseColor("#FCD5B5");
inactiveHex = Color.parseColor("#EEEEEE");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arrBgcolor = new boolean[data.length];
resetArrbg();
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
final MenuHolder holder;
row = convertView;
// convertView.setBackgroundColor(Color.BLACK);
if (row == null) {
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MenuHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tv1);
row.setTag(holder);
} else {
holder = (MenuHolder) row.getTag();
}
Menu Menu = data[position];
holder.txtTitle.setText(Menu.title);
if (arrBgcolor[position]) {
row.setBackgroundColor(activeHex);
} else {
row.setBackgroundColor(inactiveHex);
}
holder.txtTitle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
resetArrbg();
arrBgcolor[position] = true;
notifyDataSetChanged();
}
});
return row;
}
private void resetArrbg() {
for (int i = 0; i < arrBgcolor.length; i++) {
arrBgcolor[i] = false;
}
}
public class MenuHolder {
TextView txtTitle;
}
}
}
This happens because of the way ListView reuses Views when populating the list. Lets say you see three rows of the list at any given time. You "highlight" the first row by setting the background color (like you do), and scroll down. When the first row leaves the screen, Android does something smart. Instead of creating a new View for, say, the fifth row, it reuses the View from row one. That's the View you changed the background color of, so row five now got the same background color. Only the data is changed.
As for how to implement a different background color on the selected row, and the selected row only, have a look at this answer. I do believe you got to implement a custom ListAdapter, at least if you're developing for API levels lower than 11.

Custom List View with OnClickListener

I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;
public class SMSPlanner extends ListActivity {
ListView contactsListView;
private String TAG = "SMSPlanner"; CheckBox check;
int count;
List<ContactInfo> list = new ArrayList<ContactInfo>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ph = new String[3];
phType = new String[3];
LoadContactListFromPhone();
ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(contactadAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id)
{
TextView tx =(TextView)v.findViewById(R.id.firstname);
TextView ph =(TextView)v.findViewById(R.id.phone);
Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
void LoadContactListFromPhone()
{
loadlistandreturns();
}
void call()
{
Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
toast.show();
}
}
CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{
private final Activity context;
int resourceid;
List<ContactInfo> list = null;
public ContactsAdapter(Activity context, List<ContactInfo> list) {
super(context, R.layout.contactrow, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
}
LAYOUT
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="15"
android:orientation="vertical" >
<TextView
android:id="#+id/firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgStyle2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="85"
android:orientation="vertical" >
<CheckBox
android:id="#+id/check"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checked="false"
android:focusable="false"
android:focusableInTouchMode="false" >
</CheckBox>
</RadioGroup>
</LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}

Categories

Resources