Java Android Data Binding ListView - java

I have problem with list view in data binding because I don't know how to set custom ArrayAdapter in view model, and how to add onItemClick listener in view model. Someone can show how to do this? Internet have really little information about this.

Simply set the adapter for the ListView. R.id.listview must refer to your ListView defined in the Layout obviously and R.layout.listviewrow to a layout that a row should have. Furthermore add a new Instance of onItemClickListener to the ListView.
MyCustomArrayAdapter adapter = new MyCustomArrayAdapter(getActivity(), R.layout.listviewrow);
ListView lv = (ListView) getActivity().findViewById(R.id.listview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//perform desired action here
}
} );
The Adapter itself should look something like this:
public class MyCustomArrayAdapter extends ArrayAdapter<Item> {
public MyCustomArrayAdapter(Context context, int resource) {
super(context, resource);
}
public MyCustomArrayAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(resource, null);
}
Item item = getItem(position);
if (item != null) {
TextView tvFirstName = (TextView) v.findViewById(R.id.firstName);
TextView tvLastName = (TextView) v.findViewById(R.id.lastName);
if (tvFirstName != null) {
tvFirstName.setText(item.getFirstName());
}
if (tvLastName != null) {
tvLastName.setText(item.getLastName);
}
}
return v;
}

Related

How can we give custom adapter for Material Exposed Dropdown?

I tried to give custom array Adapter in Material Exposed dropdown with image and text value. DropDown is shown perfectly but when I click on those dropdown item, the selected item value is set to something like #71232. And when I set it manually like this, Second time onwards the dropdown doesn't show up.
autocompleteTextView.setOnItemClickListener(...
...
#Override
public void onItemClick{
setText(clickedItem.getText());
}
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(getContext(), list);
autoCompleteTextView.setAdapter(customArrayAdapter);
This is my CustomArrayAdapter
public class CustomArrayAdapter extends ArrayAdapter<CustomArrayAdapter.AdapterItem> {
public CustomArrayAdapter(Context context,
ArrayList<AdapterItem> itemList) {
super(context, R.layout.item_dropdown, R.id.tv_text, itemList);
}
private View initView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_dropdown, parent, false);
}
TextView tvText = convertView.findViewById(R.id.tv_text);
ImageView ivImage = convertView.findViewById(R.id.iv_image);
AdapterItem currentItem = getItem(position);
if (currentItem != null) {
tvText.setText(currentItem.text);
ivImage.setImageDrawable(getContext().getDrawable(currentItem.image));
}
return convertView;
}
}

Refresh ListView Items upon button triggered

I was having some problem when trying to refresh the items in list view after the button was triggered. Here is how I populate the listview onCreate:
public class EventChat extends Fragment {
Context context;
View eventChat;
String userID, eventID;
private ListView listview;
public ArrayList<EventComment> _commentlist = new ArrayList<EventComment>();
TextView txtDisplayCommentBy, txtDisplayDateTime, txtDisplayCommentDesc,
txtEventChat;
Button btnChatSubmit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
eventChat = inflater.inflate(R.layout.event_chat, container, false);
context = getActivity();
listview = (ListView) eventChat.findViewById(R.id.listview);
txtEventChat = (TextView) eventChat.findViewById(R.id.txtEventChat);
btnChatSubmit = (Button) eventChat.findViewById(R.id.btnChatSubmit);
btnChatSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onSubmitChatClicked();
}
});
Intent i = getActivity().getIntent();
_commentlist = (ArrayList<EventComment>) i
.getSerializableExtra("eventCommentObj");
Event eventModel = (Event) i.getSerializableExtra("eventObj");
userID = "Gab";
eventID = eventModel.getEventID();
listview.setAdapter(new ListAdapter(getActivity()));
return eventChat;
}
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
return _commentlist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.eventchat_listview_row,
null);
viewHolder = new ViewHolder();
viewHolder.txt_dcommentBy = (TextView) convertView
.findViewById(R.id.txtDisplayCommentBy);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_dcommentBy.setText(_commentlist.get(position)
.getCommentBy().trim());
return convertView;
}
}
private class ViewHolder {
TextView txt_dcommentBy;
TextView txt_ddateTime;
TextView txt_dcommentDesc;
}
}
When my button was triggered and insert a new record into database, at the same time, I wanted the list view items to be refreshed:
public void onSubmitChatClicked() {
EventComment commentModel = new EventComment();
String currentDate = EventDateTime.getCurrentDate();
String currentTime = EventDateTime.getCurrentTime();
String commentDesc = String.valueOf(txtEventChat.getText());
commentModel.setCommentBy(userID);
commentModel.setEventID(eventID);
commentModel.setCommentDate(currentDate);
commentModel.setCommentTime(currentTime);
commentModel.setCommentDesc(commentDesc);
new CreateCommentAsyncTask(context).execute(commentModel);
txtEventChat.setText("");
}
However, it does not refresh. Any ideas?
Thanks in advance.
Well this looks pretty straightforward.
First make your adapter a class member, so you can access it later:
private ListAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mAdapter = new ListAdapter(getActivity();
listview.setAdapter(mAdapter);
...
}
Then, when you submit the item, also add it to your ArrayList and update your adapter:
public void onSubmitChatClicked() {
EventComment commentModel = new EventComment();
String currentDate = EventDateTime.getCurrentDate();
String currentTime = EventDateTime.getCurrentTime();
String commentDesc = String.valueOf(txtEventChat.getText());
commentModel.setCommentBy(userID);
commentModel.setEventID(eventID);
commentModel.setCommentDate(currentDate);
commentModel.setCommentTime(currentTime);
commentModel.setCommentDesc(commentDesc);
// Add the new element to your DB
new CreateCommentAsyncTask(context).execute(commentModel);
// Add the new element to your current ArrayList
_commentlist.add(commentModel)
// Update theListView, by updating the adapter
mAdapter.notifyDataSetChanged();
txtEventChat.setText("");
}
EDIT:
Little more explanation:
When your fragment is created you are passed an array of EventComment items. I guess these are the elements from your DB. When you update the database, however, your ArrayList won't get updated, unless you reload the whole fragment. That's why you add the item to the DB, and to the list manually, and with notifyDataSetChanged, you force your adapter to update the ListView.
You cant do listview.setAdapter(new ListAdapter(getActivity())); to achieve this. You should create an instance of adapter and call adapter.add + adapter.notifyDataSetChanged
This is a very good tutorial :
http://www.vogella.com/tutorials/AndroidListView/article.html
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html

how do i change the image for each row in this list view

im new to android and java and i created a my own adapter and list view from a tutorial I was following online. I want to know how do i the image for each individual row because my adapter (from the tutorial) only has 1 image for all the rows. here is the code for my own adapter.
class HangarAdapter extends ArrayAdapter<String> {
public HangarAdapter(Context context, String[] values) {
super(context, R.layout.hangar_layout, values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater theInflater = LayoutInflater.from(getContext());
View theView = theInflater.inflate(R.layout.hangar_layout, parent, false);
String ship = getItem(position);
TextView theTextView = (TextView) theView.findViewById(R.id.textView1);
theTextView.setText(ship);
ImageView theImageView = (ImageView) theView.findViewById(R.id.imageView);
theImageView.setImageResource(R.drawable.dot);
return theView;
}
}
theImageView.setImageResource(R.drawable.dot);
This line above is what you have to change in order to use a different images;
you could potentially do something like this;
if (position == 0){
theImageView.setImageResource(R.drawable.dot);
} else if (position == 1){
theImageView.setImageResource(R.drawable.circle);
}
It also depends on the backing data.

how to write code for onitemClickListener for customized listview using BaseAdapter?

here is the code for custom listview using BaseAdapter in android its working fine:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<TaskClass> _listData;
Context _c;
public CustomListAdapter(Context context, ArrayList<TaskClass> listData) {
_listData = listData;
_c = context;
}
#Override
public int getCount() {
return _listData.size();
}
#Override
public Object getItem(int position) {
return _listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
return v;
}
}
and in activity i m binding listview with custom adapter :
listViewInstance.setAdapter(new CustomListAdapter(getApplicationContext(),taskClasslistInstance));
where "taskclasslistinstance" is my arraylist conatining data from DB its working fine
now i need to write function for listitemclick so that when user click on any listitem i can get rowid of that listitem record from Database.so after getting rowwid I can delete records from listview and from db and can edit informations
Well, we don't know about your TaskClass, but I expect you want something like this:
listViewInstance.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
TaskClass taskClass = taskClasslistInstance.get(pos);
Log.d(TAG, "Clicked on: " + taskClass)
// Do stuff with taskClass
}});
Here a small example from my project:
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LazyAdapterAlbum(getActivity(), songs);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), AlbumActivity.class);
Bundle args = new Bundle();
args.putString(AlbumActivity.ALBUM_NAME, adapter.getItem(position).getName());
i.putExtras(args);
startActivity(i);
}
});
You have to set an onClickListener on your ListView.
you can also set in getView method like below:
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform an action when this list item is clicked
}
});
return v;
}

Add custom layout to listview row

I have tried for a while now but I still can't seem to get it right. I can add a custom header to a listview but I can't add a custom row layout to a list. I want each row in the list to have the layout of the file "listitemrow.xml" but I can't seem to quite understand how to do that despite reading multiple tutorials.
Here is my code
public class PortfolioFragMent extends android.app.ListFragment{
private String[] ShareholdingNames;
private ListView mainListView ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ListView listView = new ListView(getActivity());
super.onCreate(savedInstanceState);
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.listviewheader, listView, false);
listView.addHeaderView(header, null, false);
ViewGroup listrow = (ViewGroup)inflater.inflate(R.layout.listitemrow, listView, false);
//listView.add(listitemrow); I want to do something like this
ArrayAdapter<String> array = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1);
setListAdapter(array);
ShareholdingNames= ShareholdingNames();
for (String str : ShareholdingNames)
array.add(str);
listView.setAdapter(array);
return listView;
}
private String[] ShareholdingNames(){
ShareholdingNames = new String[Portfolio.getPortfolio().count()];
for(int i=0; i < Portfolio.getPortfolio().count(); i++){
ShareholdingNames[i]= Portfolio.getPortfolio().getShareHolding(i).getName();
}
return ShareholdingNames;
}
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailShareHoldingActivity.class);
intent.putExtra("new_variable_name","value");
intent.putExtra("bookPositionInList",position);
startActivity(intent);
}
}
To do so you need to add your own custom adapter and add the line
ViewGroup listrow = (ViewGroup)inflater.inflate(R.layout.listitemrow, listView, false);
into the adapter's getView method..
public class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.listitemrow, listView, false);
}
...
return v;
}
}

Categories