Android ListView OnClickListener - java

I need to add a code responsible for action when one row from my list is clicked. I don't know if it should be OnItemClickListener or OnClickListener and how&where to write it. My app is with view holder. Here is my code:
public class JobListAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
public static class WorkViewHolder {
public TextView mJob;
public ImageView mImageAndroKorpo;
}
public JobListAdapter(Context mContext, List<String> mDane) {
super(mContext, R.layout.list_element_job, mDane);
this.mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
WorkViewHolder mHolder;
if(convertView == null) {
convertView = mInflater.inflate(R.layout.list_element_job, parent, false);
mHolder = new WorkViewHolder();
TextView mJobsName = (TextView) convertView.findViewById(R.id.nazwa_oferty);
ImageView mImageAndroKorpo = (ImageView)convertView.findViewById(R.id.list_image);
mHolder.mJob = mJobsName;
mHolder.mImageAndroKorpo = mImageAndroKorpo;
convertView.setTag(mHolder);
} else {
mHolder = (WorkViewHolder)convertView.getTag();
}
final String mWorkPosition = getItem(position);
mHolder.mJob.setText(mWorkPosition);
mHolder.mJob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here?
}
});
return convertView;
}
}
I added code where I think it should be placed. Is it ok? OnItem or OnClick? And how to use item position?
My list_element_job.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="wrap_content"
android:background="#android:color/white"
android:padding="10dp"
<CheckBox
android:id="#+id/list_checkbox"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/list_image"
android:src="#drawable/android_white_piece"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="1dp"
android:layout_height="1dp"/>
<TextView
android:text=""
android:background="#drawable/android_korpo_transparent3"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:gravity="left"
android:layout_toLeftOf="#id/list_image"
android:layout_width="0dp"
android:textSize="7pt"
android:layout_height="wrap_content"
android:id="#+id/nazwa_oferty"/>
<TextView
android:text="Details..."
android:background="#android:color/white"
android:clickable="true"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_below="#id/nazwa_oferty"
android:textSize="6pt"
android:textColor="#android:color/darker_gray"/>
</RelativeLayout>
Please help me somehow :)

Just remove the focus for the checkbox in xml like below:
<CheckBox
android:id="#+id/list_checkbox"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
because of check box focus list item click listeners wont work.

Just remove onClick from your adapter class. And add OnItemClickListener to your ListView
example:
JobListAdapter jobListAdapter = new JobListAdapter (...);
listView.setAdapter(jobListAdapter);
listView..setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});

Related

Use SeekBar in Listview item

I have a listview that has a custom adapter with a SeekBar. The view inflate fine, but when I touch the SeekBar and try to change the value, it does not responde the click, do nothing, how can I solve it?
list_itemx.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:clickable="false"
android:focusable="false"/>
<SeekBar
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:max="100"
android:progressDrawable="#drawable/seekbar_progress"
android:thumb="#drawable/seekbar_thumb"
android:clickable="false"
android:focusable="false"
/>
</LinearLayout>
my getView function inside the adapter
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (convertView == null){
view = layoutInflater.inflate(R.layout.dispositivo_list_item, parent, false);
}else{
view = convertView;
}
final int mPosition = position;
holder = new ViewHolder(view);
holder.progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int value, boolean b) {
changeProgress(mPosition,value);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
holder.name.setClickable(false);
holder.name.setFocusable(false);
holder.progress.setFocusable(false);
holder.mView.setClickable(false);
return view;
}
Edit: I found the solution. I had a notifyDataSetChanged in a function that I call inside the callback. That's what was blocking the SeekBar. Thanks for the help anyway

custom listview on fragment - can't use getActivity()

I am trying to add delete button next to my item details basing on this answer.
I tried it on a new project, it works perefect:
and when I click delete, I delete the item.
sadly, I tried to use it in my own project when my listView is in calendar_tab.xml. calendar_tab uses CompactCalendarTab.java - fragment class.
so Android Studio errored:
E:\Downloads\MyCustomAdapter.java
Error:(49, 63) error: cannot find symbol method getSystemService(String)
I tried to change
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
to
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
but with no luck.
custom_listview.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" >
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
calendar_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:id="#+id/calendar_tab"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbar_calendar"
android:background="#color/teal_300"
android:layout_alignParentTop="true"
android:padding="10sp"
android:layout_alignParentStart="true">
<ImageButton
android:id="#+id/back_button"
android:src="#mipmap/ic_arrow_back_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="goBackmain"
/>
<ImageButton
android:id="#+id/next_button"
android:src="#mipmap/ic_keyboard_arrow_left_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/showdate"
android:layout_toStartOf="#+id/showdate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="25sp"
android:textStyle="bold"
android:textColor="#color/black"
android:id="#+id/showdate"
android:layout_alignBaseline="#+id/prev_button"
android:layout_alignBottom="#+id/prev_button"
android:layout_centerHorizontal="true" />
<ImageButton
android:id="#+id/prev_button"
android:src="#mipmap/ic_keyboard_arrow_right_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/showdate"
android:layout_toEndOf="#+id/showdate" />
</RelativeLayout>
<com.github.sundeepk.compactcalendarview.CompactCalendarView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/compactcalendar_view"
android:layout_width="fill_parent"
android:layout_height="250dp"
app:compactCalendarTargetHeight="250dp"
app:compactCalendarTextSize="12sp"
app:compactCalendarBackgroundColor="#null"
app:compactCalendarTextColor="#color/blue_grey_700"
app:compactCalendarCurrentSelectedDayBackgroundColor="#color/teal_300"
app:compactCalendarCurrentDayBackgroundColor="#color/teal_600"
app:compactCalendarCurrentDayIndicatorStyle="fill_large_indicator"
app:compactCalendarEventIndicatorStyle="small_indicator"
app:compactCalendarOtherMonthDaysTextColor="#534c4c"
app:compactCalendarShouldSelectFirstDayOfMonthOnScroll="true"
android:layout_below="#+id/toolbar_calendar"
/>
<ListView
android:id="#+id/bookings_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/compactcalendar_view"
>
</ListView>
my fragment:
public class CompactCalendarTab extends Fragment {
final ListView bookingsListView = (ListView) v.findViewById(R.id.bookings_listview);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mutableBookings);
final ArrayList<String> list = new ArrayList<>();
final MyCustomAdapter adapter = new MyCustomAdapter(list, this);
bookingsListView.setAdapter(adapter);
compactCalendarView = (CompactCalendarView)
v.findViewById(R.id.compactcalendar_view);
}
my custom adapter:
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private CompactCalendarTab context;
public MyCustomAdapter(ArrayList<String> list, CompactCalendarTab context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_listview, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
Change this line
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
To this
LayoutInflater inflater = LayoutInflater.from(parent.getContext());

Get textview of custom adapter android

I have a custom view adapter with four buttons and a title that populate a ListView.
When a user clicks one of those buttons, I want to retrieve the title associated with that specific adapter.
So far I have tried retrieving the parent and getting the textView but that does not return the correct title.
So...how would I get the specific title affiliated to the adapter that has the button the user clicked on?
I'd be happy to clarify if you need more information.
Here is the layout of the adapter.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/fragment_student_home_classTitle_textView"
android:paddingTop="20dp"
android:layout_toLeftOf="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/linearLayout">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_grades"
android:background="#ffff130c" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment_student_home_grades_imageButton"
android:src="#drawable/ic_grades_512"
android:background="#00000000" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_notification_textEdit"
android:background="#ffff130c" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment_student_home_notification_imageButton"
android:src="#drawable/ic_bell_512"
android:background="#00000000" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_homework"
android:background="#ffff130c" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment_student_home_homework_imageButton"
android:src="#drawable/ic_foundation_book_bookmark_simple_black_512x512"
android:contentDescription="#string/homework_notification_icon"
android:background="#00000000" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/fragment_student_home_attendance"
android:background="#ffff130c" />
<ImageButton
android:layout_width="42dp"
android:layout_height="40dp"
android:id="#+id/fragment_student_home_attendance_imageButton"
android:src="#drawable/ic_attendance"
android:contentDescription="#string/homework_notification_icon"
android:background="#00000000" />
</LinearLayout>
</LinearLayout>
And here is the adapter where I implemented the onClick
public class ClassAdapter extends ArrayAdapter<SchoolClass> implements View.OnClickListener{
private SchoolClass aClass;
public ClassAdapter(Context context, int resource, ArrayList<SchoolClass> objects) {
super(context, resource, objects);
}
public SchoolClass getSchoolClass(){
return this.aClass;
}
public void setSchoolClass(SchoolClass schoolClass){
this.aClass = schoolClass;
}
#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.classes_adapter, null);
}
aClass = getItem(position);
if(aClass != null){
TextView title = (TextView) v.findViewById(R.id.fragment_student_home_classTitle_textView);
if(title != null){
title.setText(aClass.getTitle());
}
setSchoolClass(aClass);
}
//set buttons
ImageButton notificationsButton = (ImageButton) v.findViewById(R.id.fragment_student_home_notification_imageButton);
ImageButton gradesButton = (ImageButton) v.findViewById(R.id.fragment_student_home_grades_imageButton);
ImageButton attendanceButton = (ImageButton) v.findViewById(R.id.fragment_student_home_attendance_imageButton);
ImageButton homeworkButton = (ImageButton) v.findViewById(R.id.fragment_student_home_homework_imageButton);
notificationsButton.setOnClickListener(this);
gradesButton.setOnClickListener(this);
attendanceButton.setOnClickListener(this);
homeworkButton.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ClassActivity.class);
View parent = (View) v.getRootView();
//v.getParent() returns null when I look for the textView
TextView title = (TextView) parent.findViewById(R.id.fragment_student_home_classTitle_textView);
System.out.println("\n\n title: " + title.getText().toString() + " \n\n");
intent.putExtra("__CLASS_NAME__", title.getText().toString());
It populates a list view and if I were to click on fragment_student_home_attendance_imageButton I would want to get the fragment_student_home_classTitle_textView associated with that ClassAdapter.
Just give a idea to you, hope this can help to fix the problem :)
#Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
// ....
ImageButton notificationsButton = (ImageButton) v.findViewById(R.id.fragment_student_home_notification_imageButton);
notificationsButton.setTag(R.id.fragment_student_home_notification_imageButton);
// ....
return v;
}
#Override
public void onClick(View v) {
if(v!=null && v.getTag()!=null && v.getTag()==R.id.fragment_student_home_notification_imageButton){
// do something you like
}
}
Ok nevermind, I got it.
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ClassActivity.class);
//It's the parent of the parent OF THE parent where
//the textView lies in my layout.
View parent = (View) v.getParent().getParent().getParent();
TextView title = (TextView) parent.findViewById(R.id.fragment_student_home_classTitle_textView);
System.out.println("\n\n title: " + title.getText().toString() + " \n\n");
intent.putExtra("__CLASS_NAME__", title.getText().toString());
If there is a better way to get this solution, as it seems like a head on approach to the problem, I welcome any comments!

ListFragment OnItemClickListener

I have a list fragment displaying my custom list items which consist of a relative layout containing images and text etc.
<?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="match_parent"
android:background="#color/main_background"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:descendantFocusability="blocksDescendants" >
<ImageView
android:id="#+id/source_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#color/black"
android:layout_alignParentLeft="true"
android:contentDescription="#string/info" />
<TextView
android:id="#+id/item_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:textStyle="bold"
android:layout_toRightOf="#+id/source_image"
android:textColor="#color/black"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:textAlignment="center"
android:text="#string/item_desc" />
<ImageView
android:id="#+id/arrow_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="30dp"
android:layout_alignParentRight="true"
android:contentDescription="#string/info"
android:src="#drawable/arrow_right" />
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:layout_centerInParent="true"
android:background="#color/main_background"
android:layout_below="#+id/item_description">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="fill_horizontal"
android:layout_marginRight="20dp"
android:padding="5dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/info"
android:src="#drawable/chameleon" />
<ImageView
android:id="#+id/item_image2"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/info"
android:gravity="center"
android:src="#drawable/chameleon" />
<ImageView
android:id="#+id/item_image3"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/info"
android:gravity="center"
android:src="#drawable/chameleon" />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
I am trying to set up an OnItemClickListener so when the user clicks anywhere on the list item, a new Intent is started.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Populate list view with array objects
adapter = new HomeListItemAdapter(items, getActivity());
listView = getListView();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast toast = Toast.makeText(listView.getContext(), "CLICKED", Toast.LENGTH_SHORT);
toast.show();
}
});
}
I am attempting this as shown above but can't seem to get the OnItemClickListener to work (just testing with Toast instead of Intent for now). Where am I going wrong?
Thanks
EDIT: Added custom list adapter code
public class HomeListItemAdapter extends BaseAdapter {
private List<HomeListItem> items;
private Context context;
private int numItems = 0;
public HomeListItemAdapter(final List<HomeListItem> items, Context context) {
this.items = items;
this.context = context;
this.numItems = items.size();
}
public int getCount() {
return numItems;
}
public HomeListItem getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Get the current list item
final HomeListItem item = items.get(position);
// Get the layout for the list item
final RelativeLayout itemLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
// Set the the item picture(s)
ImageView itemImage = (ImageView) itemLayout.findViewById(R.id.item_image);
itemImage.setImageDrawable(item.getItemPic());
//Set the profile picture / source picture
ImageView sourceImage = (ImageView) itemLayout.findViewById(R.id.source_image);
sourceImage.setImageDrawable(item.getSourcePic());
// Set the text label as defined in our list item
TextView itemDesc = (TextView) itemLayout.findViewById(R.id.item_description);
AssetManager am = context.getAssets();
Typeface font = Typeface.createFromAsset(am, "Raleway-Thin.ttf");
itemDesc.setTypeface(font);
itemDesc.setText(item.getText());
return itemLayout;
}
}
Try extending ListFragment (instead of just a normal Fragment). Then you can override onListItemClicked:
public void onListItemClick(ListView l, View v, int pos, long id)
This gives you the list, view, position, and id, so you should be able to do whatever you need.
Could you try setting the HozizontalScrollView to not get focus with the XML attribute
android:focusable="false"
If you have a TextView inside the row then that will take focus when the row is clicked. This will mean that onListItemClick is not called. You either need to have an OnClickListener on the TextView or remove focus from the TextView.
See ListFragment OnListItemClick not being called
Try this sample project for costum ListFragment. It is a very good example with a costum ListFragment showing 2 types of views for phone and tablets.
http://s000.tinyupload.com/index.php?file_id=09444774931653041243
Courtsey
http://jcrazyandroider.blogspot.in/2015/01/download-links.html

Adding Custom Header to List Fragment in Android

I am trying to add a custom header that isnt clickable but will have a checkbox that will "check all" checkboxes under it.
This is my List Fragment
public class AssesmentListFragment extends ListFragment {
private static String BUNDLE_KEY_APPLICATION = "LIST_ITEM";
FastAssesmentListAdapter adapter;
View listHeader;
public AssesmentListFragment() {}
public AssesmentListFragment(Data[] data) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Data[] assestments = {new Data("Assesment ID","Name", "Date"), new Data("123456", "Assestment 2", "9/12/12"),
new Data("345672", "Assesment 3", "9/13/12"), new Data("566893", "Assesment 4", "9/14/12")};
//This is the part that makes the app crash
View header = getActivity().getLayoutInflater().inflate(R.layout.list_adapter_assesments, null);
ListView listView = getListView();
listView.addHeaderView(header);
adapter = new FastAssesmentListAdapter(getActivity(), assestments);
setListAdapter(adapter);
updateList(assestments);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void updateList(Data[] assestments) {
// NOTE: addAll is not being used to support pre-honeycomb devices
synchronized(adapter) {
adapter.clear();
adapter.addAll(assestments);
adapter.notifyDataSetChanged();
}
}
#Override
public void onListItemClick(ListView parentView, View selectedItemView, int position, long id) {
String model = (String) parentView.getItemAtPosition(position);
((FacilityActivity) getActivity()).onItemSelected(model);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putInt("curChoice", mCurCheckPosition);
}
}
This is the layout I am trying to use for header
<?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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_header_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Assesment ID" />
<TextView android:id="#+id/adapter_header_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Name" />
<TextView android:id="#+id/adapter_header_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Date"/>
<CheckBox
android:id="#+id/header_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:color="#color/defaultTextColor"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#color/BPGreenColor" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then this is the array adapter I am using:
public class FastAssesmentListAdapter extends ArrayAdapter<Data> {
private static int LAYOUT_ID = R.layout.list_adapter_with_checkbox_three_column;
private final Data[] assesments;
private final Context context;
LinearLayout listHeader;
static class ViewHolder {
protected TextView column1;
protected TextView column2;
protected TextView column3;
protected CheckBox checkbox;
}
public FastAssesmentListAdapter(Context context, Data[] assesments) {
super(context, LAYOUT_ID, assesments);
this.context = context;
this.assesments = assesments;
}
//ListFragment and array adapter will automatically call this over and over to auto populate the list
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Data item = getItem(position);
// Formulate row view (create if it does not exist yet)
View view = convertView;
if(view == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
view = inflater.inflate(LAYOUT_ID, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.column1 = (TextView) view.findViewById(R.id.adapter_textview_column1);
viewHolder.column2 = (TextView) view.findViewById(R.id.adapter_textview_column2);
viewHolder.column3 = (TextView) view.findViewById(R.id.adapter_textview_column3);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), FacilityActivity.class);
getContext().startActivity(intent);
}
});
if(viewHolder.checkbox != null) {
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
item.setSelected(isChecked);
Toast.makeText(getContext(), "Checked",
Toast.LENGTH_SHORT).show();
}
}
});
}
view.setTag(viewHolder);
viewHolder.checkbox.setTag(position);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.checkbox.setTag(position);
viewHolder.column1.setText(item.getColumn1());
viewHolder.column2.setText(item.getColumn2());
viewHolder.column3.setText(item.getColumn3());
viewHolder.checkbox.setChecked(item.isSelected());
return view;
}
}
on a side note, the onlistitemclicked in the fragment doesnt work, i have to set a listener in the adapter and then it works. any ideas on that? but mainly I need to figure out how to use a custom header and custom rows in the list view. Here is the layout for the rows
<?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="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>

Categories

Resources