I read along the code here (weblink). And the code has been modified a little bit to become like this:
FileArrayAdapter.java
public class FileArrayAdapter extends ArrayAdapter<Item> {
private Context c;
private int id;
private List<Item> items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i) {
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
// convertView = ( RelativeLayout ) inflater.inflate( resource, null );
final Item o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
setDefaultTextColor(t1);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
setDefaultTextColor(t2);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
setDefaultTextColor(t3);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null,
c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if (t1 != null)
t1.setText(o.getName());
if (t2 != null)
t2.setText(o.getData());
if (t3 != null)
t3.setText(o.getDate());
}
return v;
}
private void setDefaultTextColor(TextView tx) {
tx.setTextColor(Color.parseColor("#f8f9fe"));
}
}
And also another object I made so far:
Item.java
public class Item implements Comparable<Item>{
private String name;
private String data;
private String date;
private String path;
private String image;
public Item(String n,String d, String dt, String p, String img)
{
name = n;
data = d;
date = dt;
path = p;
image = img;
}
public String getName()
{
return name;
}
public String getData()
{
return data;
}
public String getDate()
{
return date;
}
public String getPath()
{
return path;
}
public String getImage() {
return image;
}
public int compareTo(Item o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
} }
WIth the list layout a bit customized below:
listupload_row.xml
<?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:orientation="vertical" >
<ImageView
android:contentDescription="#string/file_sharing_file_folder"
android:id="#+id/fd_Icon1"
android:layout_width="50dip"
android:layout_height="50dip" >
</ImageView>
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dip"
android:layout_toRightOf="#+id/fd_Icon1"
android:singleLine="true"
android:text="#+id/TextView01"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_marginLeft="10dip"
android:layout_toRightOf="#+id/fd_Icon1"
android:text="#+id/TextView02" >
</TextView>
<TextView
android:id="#+id/TextViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/TextView01"
android:layout_marginLeft="5dip"
android:text="#+id/TextViewDate" >
</TextView>
</RelativeLayout>
My question is:
I know If I want to put Checkbox then I should put it under the XML (layout).
But my case is, I want to make the longClick available for showing the Checkboxes.
And how to do that?
If I simply add this code below, of course it will set the ListView to have onLongClick event....
dList.setLongClickable(true);
dList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// show the checkbox of each lines
return true;
}
});
But to make it once onLongClick executed, how do I show the Combobox? and vice versa....
One possible solution is to hide/show the checkbox based on a flag that is toggled when an item receives a long click.
Do something like this in your adapter's getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
if(showCheckBoxes) {
v.findViewById(R.id.checkbox).setVisible(View.VISIBLE);
} else {
v.findViewById(R.id.checkbox).setVisible(View.GONE);
}
...
}
and then in your long click listener:
dList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
showCheckBoxes = !showCheckBoxes;
fileArrayAdapter.notifyDataSetChanged();
return true;
}
});
Its simple add checkbox in xml and make visibility gone
android:visibility="gone"
And declare a radiobox in FileArrayAdapter class as you did with textbox and the put your
onItemLongClickListener();
In that check if checkbox is visible then make it disappear or if not visible the make it visible.
if(cb.isVisible()){
cb.setVisibility(View.GONE);
}else{
cb.setVisibility(View.VISIBLE);
}
Thats's it.
Related
I'm trying to upgrade my PopupMenu so it would come with icons and custom styles.
I have created a new layout for it
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:id="#+id/layout_sharea"
android:background="#drawable/share"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip"
android:layout_width="wrap_content"
android:layout_height="50.0dip"
android:onClick="share">
<TextView
android:id="#+id/sharetexta"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/share"
android:drawableLeft="#drawable/share_button"
android:drawablePadding="10.0dip"
android:layout_centerVertical="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/layout_shareb"
android:background="#drawable/share"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip"
android:layout_width="wrap_content"
android:layout_height="50.0dip"
android:layout_below="#+id/layout_sharea"
android:onClick="share">
<TextView
android:id="#+id/sharetextb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/share"
android:drawableLeft="#drawable/share_button"
android:drawablePadding="10.0dip"
android:layout_centerVertical="true" />
</RelativeLayout>
</RelativeLayout>
I want the PopupMenu to be customized (to be this layout) like in this picture
A PopupMenu is meant for displaying Menus and there really isn't a good way of customizing the appearance of the menu items. If you want something more flexible, your answer is ListPopupWindow.
private static final String TITLE = "title";
private static final String ICON = "icon";
private List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
// Use this to add items to the list that the ListPopupWindow will use
private void addItem(String title, int iconResourceId) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TITLE, title);
map.put(ICON, iconResourceId);
data.add(map);
}
// Call this when you want to show the ListPopupWindow
private void showListMenu(View anchor) {
ListPopupWindow popupWindow = new ListPopupWindow(this);
ListAdapter adapter = new SimpleAdapter(
this,
data,
android.R.layout.activity_list_item, // You may want to use your own cool layout
new String[] {TITLE, ICON}, // These are just the keys that the data uses
new int[] {android.R.id.text1, android.R.id.icon}); // The view ids to map the data to
popupWindow.setAnchorView(anchor);
popupWindow.setAdapter(adapter);
popupWindow.setWidth(400); // note: don't use pixels, use a dimen resource
popupWindow.setOnItemClickListener(myListener); // the callback for when a list item is selected
popupWindow.show();
}
Here is my demo for custom ListPopupWindow by custom adapter
Model
public class ListPopupItem {
private String title;
private int imageRes;
public ListPopupItem(String title, int imageRes) {
this.title = title;
this.imageRes = imageRes;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageRes() {
return imageRes;
}
}
ListAdapter
public class ListPopupWindowAdapter extends BaseAdapter {
private List<ListPopupItem> items;
public ListPopupWindowAdapter(List<ListPopupItem> items) {
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListPopupItem getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_popup, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(getItem(position).getTitle());
holder.ivImage.setImageResource(getItem(position).getImageRes());
return convertView;
}
static class ViewHolder {
TextView tvTitle;
ImageView ivImage;
ViewHolder(View view) {
tvTitle = view.findViewById(R.id.text);
ivImage = view.findViewById(R.id.image);
}
}
}
item_list_popup.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="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
tools:text="Title"
/>
</LinearLayout>
Finally, show ListPopupWindow
(In this demo, I show MATCH_PARENT popup here, you can show a specific with for popup (eg: 100px, 200px,...)
If you set popup width = WRAP_CONTENT, popup width will equals ANCHOR width)
private void showListPopupWindow(View anchor) {
List<ListPopupItem> listPopupItems = new ArrayList<>();
listPopupItems.add(new ListPopupItem("Menu 1", R.mipmap.ic_launcher));
listPopupItems.add(new ListPopupItem("Menu 2", R.mipmap.ic_launcher));
listPopupItems.add(new ListPopupItem("Menu 3", R.mipmap.ic_launcher));
final ListPopupWindow listPopupWindow =
createListPopupWindow(anchor, ViewGroup.LayoutParams.MATCH_PARENT, listPopupItems);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listPopupWindow.dismiss();
Toast.makeText(MainActivity.this, "clicked at " + position, Toast.LENGTH_SHORT)
.show();
}
});
listPopupWindow.show();
}
private ListPopupWindow createListPopupWindow(View anchor, int width,
List<ListPopupItem> items) {
final ListPopupWindow popup = new ListPopupWindow(this);
ListAdapter adapter = new ListPopupWindowAdapter(items);
popup.setAnchorView(anchor);
popup.setWidth(width);
popup.setAdapter(adapter);
return popup;
}
Example using
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showListPopupWindow(view);
}
});
DEMO
I'm trying to implement a selection activity for a given list of items. Each item is checkable, so I have an item with a TextView and a CheckBox. I implemented a ListView for displaying all the options and a Spinner for showing only the "Top Ten" choices, as a subset of the same list. For now I'm showing all the items in both ListView and Spinner.
I want for the items in the ListView to update when the user selects an item in the Spinner (Note: The reverse path works fine, as the Spinner grabs the updated ArrayList each time it dropsdown).
I tried to implement setOnItemSelectedListener for my Spinner, and to call notifyOnDataSetChanged() for my ListViewAdapter inside the Listener. But the Listener is only called on collapse and I get a weird (maybe unrelated) warning message.
The onItemSelectedListener for the Spinner only runs when the Spinner gets collapsed. But notifyOnDataSetChanged() seems to ignore the checked status of the items as a change. How can I make the first option run everytime I check an item and have the change get properly received by the ListAdapter?
Here's the Activity.java code:
public class TriageReasonActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_triage_reason);
final String[] select_qualification = {
"Select Qualification", "10th / Below", "12th", "Diploma", "UG",
"PG", "Phd"};
Spinner spinner = (Spinner) findViewById(R.id.top_reasons_spinner);
ListView symptoms_list = (ListView) findViewById(R.id.view_list_symptoms);
ArrayList<Symptoms> listVOs = new ArrayList<>();
for (int i = 0; i < select_qualification.length; i++) {
Symptoms reason = new Symptoms();
reason.setTitle(select_qualification[i]);
reason.setSelected(false);
listVOs.add(reason);
}
SymptomsListAdapter mListAdapter = new SymptomsListAdapter(this, 0,
listVOs);
SymptomsSpinnerAdapter mSpinnerAdapter = new SymptomsSpinnerAdapter(this, 0,
listVOs);
symptoms_list.setAdapter(mListAdapter);
spinner.setAdapter(mSpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.i("Item selected", "but not cahnged");
symptoms_list.invalidateViews();
mListAdapter.notifyDataSetInvalidated();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
Log.i("Not item selected", "but actually it did");
}
});
}
The SpinnerCustom Adapter code:
public class SymptomsSpinnerAdapter extends ArrayAdapter<Symptoms>{
private Context mContext;
private ArrayList<Symptoms> listState;
private SymptomsSpinnerAdapter myAdapter;
private boolean isFromView = false;
/*#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
//mNotifyOnChange = true;
}*/
public SymptomsSpinnerAdapter(Context context, int resource, List<Symptoms> objects) {
super(context, resource, objects);
this.mContext = context;
this.listState = (ArrayList<Symptoms>) objects;
this.myAdapter = this;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(mContext);
convertView = layoutInflator.inflate(R.layout.item_reasons, null);
holder = new ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mTextView.setText(listState.get(position).getTitle());
// To check weather checked event fire from getview() or user input
isFromView = true;
holder.mCheckBox.setChecked(listState.get(position).isSelected());
isFromView = false;
if ((position == 0)) {
holder.mCheckBox.setVisibility(View.INVISIBLE);
} else {
holder.mCheckBox.setVisibility(View.VISIBLE);
}
holder.mCheckBox.setTag(position);
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
if (!isFromView) {
listState.get(position).setSelected(isChecked);
}
}
});
return convertView;
}
#Override
public int getCount() {
return listState.size();
}
#Override
public Symptoms getItem(int position) {
if( position < 1 ) {
return null;
}
else {
return listState.get(position-1);
}
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
private TextView mTextView;
private CheckBox mCheckBox;
}
}
Here's the (almost identical) ListAdapter:
public class SymptomsListAdapter extends BaseAdapter implements ListAdapter {
private Context mContext;
private ArrayList<Symptoms> listState;
private boolean isFromView = false;
public SymptomsListAdapter(Context context, int resource, List<Symptoms> objects) {
this.mContext = context;
this.listState = (ArrayList<Symptoms>) objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(mContext);
convertView = layoutInflator.inflate(R.layout.item_reasons, null);
holder = new SymptomsListAdapter.ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (SymptomsListAdapter.ViewHolder) convertView.getTag();
}
holder.mTextView.setText(listState.get(position).getTitle());
// To check weather checked event fire from getview() or user input
isFromView = true;
holder.mCheckBox.setChecked(listState.get(position).isSelected());
isFromView = false;
if ((position == 0)) {
holder.mCheckBox.setVisibility(View.INVISIBLE);
} else {
holder.mCheckBox.setVisibility(View.VISIBLE);
}
holder.mCheckBox.setTag(position);
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
if (!isFromView) {
listState.get(position).setSelected(isChecked);
}
}
});
return convertView;
}
#Override
public int getCount() {
return listState.size();
}
#Override
public Symptoms getItem(int position) {
if( position < 1 ) {
return null;
}
else {
return listState.get(position-1);
}
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
public TextView mTextView;
public CheckBox mCheckBox;
}
}
And here's the warning I'm getting:
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
EDIT: Adding the layouts and the model class in case they may cause an issue:
Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="demo.hb.activity.visit.TriageReasonActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textFontWeight="6dp"
android:textSize="30sp"
android:layout_margin="20dp"
android:textAlignment="center"
android:textColor="#000000"
android:text="What is the reason for your visit?" />
<Spinner
android:id="#+id/top_reasons_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_list_symptoms"
android:layout_above="#+id/next_btn"
android:layout_alignParentTop="true"/>
</RelativeLayout>
</LinearLayout>
</FrameLayout>
Item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:text="text"
android:textAlignment="gravity" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Model Class:
public class Symptoms {
private String title;
private boolean selected;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
The reason that nothing is changing is because you haven't implemented the method to handle the data set changes. You need to handle how the data is reloaded in your adapter:
public class SymptomsListAdapter extends BaseAdapter implements ListAdapter {
...
public void refreshData(ArrayList<Symptoms> objects){
this.listState = (ArrayList<Symptoms>) objects;
notifyDataSetChanged();
}
...
}
This link does a great job of explaining how the notifyDataSetInvalidated() works (or in your case, why it's not working).
I need help to make listview adapter. Below is code please make the adapter both value name with roomid.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
RoomModel.java
public class RoomModel {
private String name, id, roomid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getroomId() {
return roomid;
}
public void setroomId(String roomid) {
this.roomid = roomid;
}
}
try the following Adapter......
public class MyAdapter extends BaseAdapter {
Context con;
ArrayList<your type> mlist;
RoomModel sched;
public MyAdapter(Context con,ArrayList<your type> mlist )
{
this.con=con;
this.mlist=mlist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mlist.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mlist[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sched=mlist.get(position);
LayoutInflater inflater=(LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.your_layout,parent,false);
TextView tv1=(TextView)convertView.findViewById(R.id.your_textview);
tv1.setText(sched.getId());
TextView tv2=(TextView)convertView.findViewById(R.id.your_textview);
tv2.setText(sched.getName());
TextView tv3=(TextView)convertView.findViewById(R.id.your_textview);
tv3.setText(sched.getroomId());
return convertView;
}
}
and change the following code.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
MyAdapter adapter=new MyAdapter(this,CustomListViewValuesArr);
listView.setAdapter(adapter);
OK as requested by Sandeep, I will give you simple hint but I can't give you full codes that you can directly copy and paste. Just follow instructions
Create an XML file for single item of the list which may have certain elements as you need, for example It's single_item.xml which has 3 TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Sample Id"
android:textColor="#0414f4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="10sp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Sample Title"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sample body"
android:textSize="16sp"/>
</LinearLayout>
and after getting the reference of listView from main layout set the adapter like this, And here modelList is an ArrayList.
mAdapter = new CustomAdapter(MainActivity.this, R.layout.single_item, modelList);
mAdapter.notifyDataSetChanged();
mListView.setAdapter(mAdapter);
Then the class CustomAdapter looks like this
public class CustomAdapter extends ArrayAdapter<Model> {
ArrayList<Model> modelList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Model> objects) {
super(context, resource, objects);
this.modelList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.single_item,parent,false);
}
// Lookup view for data population
TextView tvId = (TextView) convertView.findViewById(R.id.tvId);
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvBody = (TextView) convertView.findViewById(R.id.tvBody);
// Populate the data into the template view using the data object
tvId.setText(String.valueOf(model.getId()));
tvTitle.setText(model.getroomId());
tvBody.setText(model.getName());
// Return the completed view to render on screen
return convertView;
}
}
NOTE : I have commented and made it simple as possible to help you. Hope this may help. You can comment if any problem raised.
I know this question is asked several times here, and i go through all the answer and tried implementing it in my code, but the result is fail. That's why i have posted a new question to get my code run. Question is simple whenever i want to trigger listView.setOnItemClickListener(this). It is not fired. I tried each suggestion given in stackoverflow but not able to solve the issue.
Code i used are
visitor_list_fragment.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/node_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:textIsSelectable="false"
android:textSize="20sp" />
<ListView
android:id="#+id/visitor_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:cacheColorHint="#00000000"
android:dividerHeight="5dp"
android:listSelector="#00000000"
android:scrollingCache="true"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
visitor_list_item.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/photo_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:contentDescription="#string/image_name"
android:focusable="false" />
<TextView
android:id="#+id/profile_info_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:focusable="false"
android:textColor="#android:color/black"
android:textIsSelectable="false"
android:textSize="20sp" />
</LinearLayout>
Code where i called onItemClickListener
public class VisitorListFragment extends Fragment implements OnItemClickListener
{
private TextView m_NodeName;
private ListView m_VisitorListView;
private VisitorListAdapter m_VisitorNodeListAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.visitor_list_fragment, null);
m_NodeName = (TextView)view.findViewById(R.id.node_name_textView);
m_VisitorNodeListAdapter = new VisitorListAdapter(getActivity().getApplicationContext());
m_VisitorListView = (ListView)view.findViewById(R.id.visitor_list_view);
// Displaying header & footer in the list-view
TextView header = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
header.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addHeaderView(header, null, false);
TextView footer = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
footer.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addFooterView(footer, null, false);
m_VisitorListView.setAdapter(m_VisitorNodeListAdapter);
m_VisitorListView.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String nodeName = m_VisitorNodeListAdapter.getNodeName(position);
System.out.println(nodeName);
}
}
AdapterClass
public class VisitorListAdapter extends BaseAdapter
{
private HashMap<String, String> m_ProfileImagePath;
private HashMap<String, String> m_ProfileInfo;
private ArrayList<String> m_NodeName;
private LayoutInflater m_Inflater=null;
public VisitorListAdapter(Context context)
{
super();
m_ProfileImagePath = new HashMap<String, String>();
m_ProfileInfo = new HashMap<String, String>();
m_NodeName = new ArrayList<String>();
m_Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getItem(int arg0)
{
return null;
}
public int getCount()
{
return m_NodeName.size();
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int position)
{
return false;
}
public String getNodeName(int position)
{
return m_NodeName.get(position);
}
public class ViewHolder
{
TextView profileInfoTextView;
ImageView profileImageView;
}
public void addProfileInfo(String nodeName, String profileInfo)
{
boolean found = false;
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
found = true;
}
}
if(found == false)
{
m_NodeName.add(nodeName);
m_ProfileInfo.put(nodeName, profileInfo);
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
}
public void addProfileImagePath(String nodeName, String profileInfoImagePath)
{
m_ProfileImagePath.put(nodeName, Utilities.CHORD_FILE_PATH + "/" + profileInfoImagePath);
notifyDataSetChanged();
}
public void removeNode(String nodeName)
{
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
m_NodeName.remove(i);
m_ProfileInfo.remove(nodeName);
m_ProfileImagePath.remove(nodeName);
}
}
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public void clearAll()
{
m_ProfileImagePath.clear();
m_NodeName.clear();
m_ProfileInfo.clear();
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = m_Inflater.inflate(R.layout.visitor_list_item, null);
holder.profileImageView = (ImageView)convertView.findViewById(R.id.photo_view);
holder.profileInfoTextView = (TextView)convertView.findViewById(R.id.profile_info_textview);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
// Put the code in an async task
new ImageLoaderTask(position, holder).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return convertView;
}
class ImageLoaderTask extends AsyncTask<URL, Integer, Long>
{
private int position;
private ViewHolder holder;
ImageLoaderTask(int position, ViewHolder holder)
{
this.position = position;
this.holder = holder;
}
#Override
protected void onPreExecute()
{
String loadPath = m_ProfileImagePath.get(m_NodeName.get(position));
Bitmap bitmap = BitmapFactory.decodeFile(loadPath);
if(bitmap != null)
{
holder.profileImageView.setImageBitmap(bitmap);
}
holder.profileInfoTextView.setText(m_ProfileInfo.get(m_NodeName.get(position)));
}
#Override
protected Long doInBackground(URL... urls)
{
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
}
#Override
protected void onPostExecute(Long result)
{
}
}
}
public boolean isEnabled(int position)
{
return false;
}
This should be true for all active elements!
Try removing
android:focusable="false" and
android:textIsSelectable="false"
from listView_item.xml file...
Check if your m_VisitorListView isn't null (debugging mode).
Check the import onItemClick, should be AdapterView.OnItemClickListener
If you still facing this issue try implementing it anonymously:
m_VisitorListView .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
} );
I am creating an app that has a contacts list inside it. Currently the list works and displays all of my contacts just the way i want it. However i need to add a click function to them. I want to call them once i press one of them. How can i do that? I already have an onListItemClick method in the same activity due to an rss reader. How can i filter it out? Take a look at my code:
//Load contacts into ListView on people screen
contactListView = (ListView) findViewById(R.id.contactsListView);
contactstock = new ArrayList<ContactStock>();
mCursor = managedQuery(ContactsContract.Data.CONTENT_URI, null, Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'", null,
ContactsContract.Data.DISPLAY_NAME + " ASC");
int number = mCursor.getColumnIndex(Phone.NUMBER);
int name = mCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
while (mCursor.moveToNext()) {
String phName = mCursor.getString(name);
String phNumber = mCursor.getString(number);
contactstock.add(new ContactStock(phName, phNumber));
}
contactListView.setAdapter(new ContactListAdapter(MainActivity.this,
contactstock));
ContactStock.java:
public class ContactStock {
private String name;
private String number;
public ContactStock(String name, String number) {
this.name = name;
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getNumber() {
return this.number;
}
}
ContactListAdapter.java:
public class ContactListAdapter extends ArrayAdapter {
private final Activity activity;
private final List stocks;
public ContactListAdapter(Activity activity, List objects) {
super(activity, R.layout.listview_detail_tab_contact_list, objects);
this.activity = activity;
this.stocks = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ContactStockView sv = null;
if (rowView == null) {
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(
R.layout.listview_detail_tab_contact_list, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sv = new ContactStockView();
sv.name = (TextView) rowView.findViewById(R.id.contact_name);
sv.number = (TextView) rowView.findViewById(R.id.contact_number);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sv);
} else {
sv = (ContactStockView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
ContactStock currentStock = (ContactStock) stocks.get(position);
sv.name.setText(currentStock.getName());
sv.number.setText(currentStock.getNumber());
// TODO Auto-generated method stub
return rowView;
}
protected static class ContactStockView {
protected TextView name;
protected TextView number;
}
}
My current listview code(for rss viewer):
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = Uri.parse(links.get(position).toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
ListView row 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="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/defaultavatar" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:text="Who am I"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="000000000" />
</LinearLayout>
</LinearLayout>
I got the phone number from the contact i tapped by using this code:
contactstock.get(arg2).getNumber()
You should set both listviews and set onItemClickListener for each one.
ListView l1 = (ListView)findViewById(R.id.list1);
ListView l2 = (ListView)findViewById(R.id.list2);
// listener for the first one
l1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
// listener for the other
l2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
I think what you say is you are having 2 listview.
You can use setOnItemClickListener to the listview instead of using onListItemClick.
contactListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}});