ListView doesn't react on clicks - java

i am a beginer android-developer and i need some help:
There is a Fragment in my Project - TasksFragment, there is a ListView element on it. On ListView, using ArrayAdapter Items are formed by a custom layout for Item and then added to ListView. The problem is, that ListView don't react on click processing events.
Here are the code fragments:
TaskAdapter class...
public class TaskAdapter extends ArrayAdapter<Task> {
public TaskAdapter(ArrayList<Task> tasks) {
super(getActivity(), 0, tasks);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_task, null);
}
Task task = getItem(position);
TextView titleTextView = (TextView) convertView.findViewById(R.id.task_list_item_titleTextView);
titleTextView.setText(task.getTitle());
CheckBox solvedCheckBox = (CheckBox) convertView.findViewById(R.id.task_list_item_solvedCheckBox);
solvedCheckBox.setChecked(task.isSolved());
return convertView;
}
}
ItemClick fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tasks_fragment, null);
mTasks = TaskLab.get(getActivity()).getTasks();
final ListView lvMain = (ListView) view.findViewById(R.id.listViewTasks);
lvMain.setClickable(true);
TaskAdapter adapter = new TaskAdapter(mTasks);
setHasOptionsMenu(true);
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Task task = (Task)lvMain.getItemAtPosition(position);
Toast.makeText(getActivity().getApplicationContext(), task.getTitle() + " was clicked", Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), AddTaskActivity.class);
startActivity(i);
}
});
return view;
}
XML Layout for List_Item_Task
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/task_list_item_solvedCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentRight="true"
android:enabled="false"
android:padding="4dp"/>
<TextView
android:id="#+id/task_list_item_titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/task_list_item_solvedCheckBox"
android:textStyle="bold"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="22dp"/>
</RelativeLayout>
Xml layout for tasks_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3f638b">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewTasksFragmentHeader"
android:text="Задачи"
android:textSize="30dp"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listViewTasks" />
</LinearLayout>

Yes your listview is not clickable.
Just add this in your checkbox layout
android:focusable="false"
Your items xml should look like this
<?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" >
<CheckBox
android:id="#+id/task_list_item_solvedCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" //Add this
android:layout_alignParentRight="true"
android:gravity="center"
android:padding="4dp" />
<TextView
android:id="#+id/task_list_item_titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/task_list_item_solvedCheckBox"
android:paddingBottom="5dp"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:paddingTop="5dp"
android:textSize="22dp"
android:textStyle="bold" />
Now it should work. I have tested it :)

Related

Not able to put recycler view as ExpandableListView header layout

I want to display a recycler view inside the ExpandableListView header item.But I am getting an issue my header is not clickable when I put a recycler view in it.
Here is my code:-
header.xml
<?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="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1"
android:padding="8dp"
android:background="#color/grey">
<TextView
android:id="#+id/lblListHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="5dp"
android:textSize="15dp"
android:layout_weight=".25"
android:text="#"
android:textColor="#color/ModeltitleColor" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".65"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/ivRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
/>
</LinearLayout>
<ImageView
android:id="#+id/iv_group_indicator"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:layout_weight=".10"
android:src="#drawable/ic_arrow_drop_down_black_24dp" />
</LinearLayout>
</LinearLayout>
here I am setting the group:-
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.zonal_list_group, viewGroup, false);
}
TextView textView = view.findViewById(R.id.lblListHeader);
RecyclerView recyclerView=view.findViewById(R.id.ivRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
ZoneNameAdapter zoneNameAdapter =new ZoneNameAdapter(zonalSnapShotResponse.keyFigureDataGroups.get(i).zones,context);
recyclerView.setAdapter(zoneNameAdapter);
ImageView imageView = view.findViewById(R.id.iv_group_indicator);
textView.setText(zonalSnapShotResponse.keyFigureDataGroups.get(i).dataGroup);
imageView.setImageResource(R.drawable.ic_arrow_drop_down_black_24dp);
if (b) {
imageView.setRotation(180f);
} else {
imageView.setRotation(0f);
}
return view;
}
getChildItemCount does not get called when I put recycler view in the header.
I have tried multiple solutions but noting worked for me.Please help

Add item to RecyclerView from AlertDialog input

I'm currently having trouble with adding a second+ items to a RecyclerView after inputting data in an alertdialog box.
I can enter 1 set of data but when I try to add more, it doesn't do anything.
This is my Java file for the fragment i'm working with:
public class tab1Expenses extends Fragment {
List<ExRow> expenseList = new ArrayList();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
EditText txtExName;
EditText txtExAmount;
public void expenseData() {
String Na = txtExName.getText().toString();
String Am = txtExAmount.getText().toString();
ExRow exs = new ExRow(Na, Am);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mAdapter = new ExpensesAdapter(expenseList);
final RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
expenseData();
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
}
And the Java file for the adapter:
public class ExpensesAdapter extends RecyclerView.Adapter<ExpensesAdapter.MyViewHolder> {
private List<ExRow> expenseList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, amount;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.name);
amount = (TextView) view.findViewById(R.id.amount);
}
}
public ExpensesAdapter(List<ExRow> expenseList) {
this.expenseList = expenseList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.expense_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ExRow expense = expenseList.get(position);
holder.title.setText(expense.getTitle());
holder.amount.setText(expense.getAmount());
}
#Override
public int getItemCount() {
return expenseList.size();
}
}
The XML to format the recyclerview list items:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/name"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentLeft="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/amount"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="wrap_content" />
</RelativeLayout>
And this is the XML for the fragment:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses"
android:background="#android:color/darker_gray">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="450dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="450dp"
android:scrollbars="vertical"
android:keepScreenOn="true"
android:isScrollContainer="true" />
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
This is what I currently see AFTER adding a 2nd input
You can't do so:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</ScrollView>
Your RecyclerView has 0 height now. You need to add a some fixed height to it and set a scroll behaviour. Or you can use NestedScrollView or write LayoutManager with the full height expansion.
See this thread for details.
ADDED
Use this XML instead of your but I wrote it without IDE so it can contain some errors.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses"
android:background="#android:color/darker_gray">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:keepScreenOn="true" />
<Button
android:text="Add Expense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_gravity="bottom|center_horizontal"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
</FrameLayout>
I solved my problem. It was to do with the height of the relative layout for the recycler items. It was on match parent, i switched to wrap content and it now displays the inputs on the screen

setOnClickListener not firing with custom adapter and custom ListView

I've been spending a few hours on a problem and I still can't figure it out. The setOnClickListener in HotelOverviewFragment is not firing when I click an item in my ListView. However, the setOnClickListener does work from my custom adapter (NowArrayAdapter).
My question is: why the setOnClickListener not working in HotelOverviewFragment (Class where the ListView is shown)?
Here's a list of what I've tried:
Setting android:focusable="false", android:focusableInTouchMode="false", android:descendantFocusability="blocksDescendants" in the hotel_row_layout.xml and fragment_hotel_overview.xml.
Setting android:clickable on true and false. Both didn't work.
Changing from BaseAdapter implementation to arrayAdapter.
I tried different listeners in HotelOverviewFragment: setOnClickListener, setOnItemClickListener, setOnItemSelectedListener and setOnTouchListener. Unfortunately, none of those worked for me.
Here's my code:
Custom adapter
public class NowArrayAdapter extends ArrayAdapter<String> {
private Context context;
private ArrayList<String> values;
private Typeface typeface;
private static Hashtable fontCache = new Hashtable();
private LayoutInflater inflater;
private TextView item;
public NowArrayAdapter(Context context, ArrayList<String> commandsList) {
super(context, R.layout.hotel_row_layout, commandsList);
this.context = context;
values = new ArrayList<String>();
values.addAll(commandsList);
typeface = getTypeface(this.context, "fonts/Roboto-Light.ttf");
inflater = LayoutInflater.from(this.context);
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public View getView(int position, View convertView, ViewGroup parent) {
String myText = getItem(position);
if(convertView == null) {
convertView = inflater.inflate(R.layout.hotel_row_layout, parent, false);
item = (TextView) convertView.findViewById(R.id.maps_button);
item.setTypeface(typeface);
convertView.setTag(item);
} else {
item = (TextView) convertView.getTag();
}
item.setText(myText);
//myListItem.descText.setTextSize(14);
convertView.setOnClickListener(new View.OnClickListener() {
// WORKS!
#Override
public void onClick(View view) {
Log.d("click", "Don't look at me!");
}
});
return convertView;
}
}
Fragment
public class HotelOverviewFragment extends Fragment {
private static Hashtable fontCache = new Hashtable();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_hotel_overview, container, false);
ListView list = (ListView) v.findViewById(android.R.id.list);
// Set up listview and buttons
setUp(v, list);
// Inflate the layout for this fragment
return v;
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public void setUp(View v, ListView l){
TextView address = (TextView) v.findViewById(R.id.content);
TextView header = (TextView) v.findViewById(R.id.header);
TextView hotelName = (TextView) v.findViewById(R.id.hotelName);
Typeface typeface = getTypeface(getActivity(), "fonts/Roboto-Light.ttf");
address.setText("some street \nZipCode, City \nCountry \nEmail \nphoneNumber");
address.setTypeface(typeface);
header.setText("Hotel info");
header.setTypeface(typeface);
header.setTextSize(20);
hotelName.setText("Hotel name");
hotelName.setTypeface(typeface);
// Set up button
ArrayList<String> n = new ArrayList<String>();
n.add(0, "More info");
// Show button
NowArrayAdapter adapter = new NowArrayAdapter(getActivity(), n);
l.setAdapter(adapter);
// THIS IS THE STUFF I'VE BEEN TRYING
try {
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("click", "Success");
}
});
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
});
l.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
l.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("click", "Success");
return false;
}
});
}catch (Exception e){
Log.d("click", e + "");
}
}
}
Layout xml of HotelOverviewFragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example"
android:background="#ffebebeb">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="#drawable/banner"
android:id="#+id/hotelBanner"
android:layout_gravity="top"
android:adjustViewBounds="false"
android:scaleType="fitXY" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hotelname"
android:id="#+id/hotelName"
android:gravity="center"
android:textSize="40dp"
android:layout_alignBottom="#+id/hotelBanner"
android:layout_alignParentRight="false"
android:layout_alignParentLeft="false"
android:textColor="#ffc4c4c4"
android:layout_marginBottom="5dp" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="0dp"
android:background="#drawable/header_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/header"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Header"
android:layout_toRightOf="#+id/headerImage"
android:layout_centerVertical="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/headerImage"
android:src="#drawable/ic_action_live_help"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:background="#drawable/content_card">
<TextView
android:id="#+id/content"
android:layout_gravity="left|center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
The custom xml for a listview item
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/content_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/maps_button"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
<ImageView
android:src="#drawable/ic_action_arrow_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="false"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="false"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</LinearLayout>
Thanks in advance.
Thanks to Daniel Nugent's suggestion I got it working. Removing the convertView.setOnClickListener() is part of the answer. I think it was blocking the other listeners in the HotelOverviewFragment.
My next mistake was that I used setOnClickListener on a ListView for testing.
setOnClickListener should be used for buttons not ListViews.
So after removing setOnClickListener all the other listeners started working.
Thanks for your time.

Errors on Adding ListView to Fragment

I am trying to add a listview to an existing android fragment. I made a layout xml file for items in the listview, modified the previous fragment.xml, wrote a new arrayadapter and added something to the fragment.java. But whenever I call the notifyDataSetChanged() method in the fragment.java, I got an error: android.content.res.Resources$NotFoundException: String resource ID #0x0, and then the app crashes. Below please find my codes.
layout.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"
android:paddingBottom="7dp">
<ImageView
android:layout_width="72dp"
android:layout_height="72dp"
android:id="#+id/iv_checkIcon"
android:layout_margin="7dp"
android:background="#EEEEEE"
android:contentDescription="Provider icon"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_toRightOf="#id/iv_checkIcon"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="5dp"
>
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkName"
android:text="Provider name"
android:textSize="20dp"
/>
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkInDate"
android:text="Check In Date"
android:textSize="14dp"
android:textColor="#888888"
android:layout_marginTop="4dp"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_checkPoints"
android:layout_alignParentRight="true"
android:text="100分"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textSize="18dp"
android:textColor="#CF1A12"
/>
</RelativeLayout>
fragment.xml
<FrameLayout 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=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</FrameLayout>
Arrayadapter.java
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRecList;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRecList)
{
super(context, resourceId, checkInRecList);
this.resourceId = resourceId;
this.context = context;
this.checkInRecList = checkInRecList;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_checkName);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkInDate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_checkPoints);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_checkIcon);
CheckInRecord.CheckInRec checkInRec = checkInRecList.get(position);
textViewName.setText(checkInRec.providerName);
textViewCheckInDate.setText(checkInRec.checkInDate);
textViewPoints.setText(checkInRec.providerPoints);
ImageLoader.getInstance().displayImage(checkInRec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRecList.get(position).isPrize);}
}
fragment.java
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRecList = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) fragmentView.findViewById(R.id.tv_name);
textViewPoints = (TextView) fragmentView.findViewById(R.id.tv_points);
ListView listViewRec = (ListView) fragmentView.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity(), R.layout.row_record, checkInRecList);
listViewRec.setAdapter(recordArrayAdapter);
return fragmentView;
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
this.checkInRecList.clear();
this.checkInRecList.addAll(checkInRecord.checkInRecList);
recordArrayAdapter.notifyDataSetChanged();
}
}
}
Make sure checkInRec.providerName, checkInRec.checkInDate and checkInRec.providerPoints values that you set as TextView text have a type of String and cast it to String if it's integer.
// cast to String if checkInRec.checkInDate is integer
textViewPoints.setText(String.valueOf(checkInRec.providerPoints));
UPD:
It seems ListView is located behind header view. Try to change root view of fragment.xml from FrameLayout to LinearLayout with android:orientation="vertical" attribute. Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</LinearLayout>

Adding views programmatically with a xml layout

I want to programmatically add a view to ScrollView that is apart of a Fragment layout.
I have attempeted the following code:
public class MessageDetail extends Fragment {
View layout;
TextView messageText;
Conversation conversation;
List<Message> messages;
LayoutInflater inflater;
ViewGroup container;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
this.inflater = inflater;
this.container = container;
layout = inflater.inflate(R.layout.messenger_detail, container,
false);
messageText = (TextView) layout.findViewById(R.id.tvMessage);
return layout;
}
public void loadConversation(Conversation conversation) {
messageText.setText(conversation.getSubject());
LinearLayout messagesView = (LinearLayout)layout.findViewById(R.id.llMessageDetail);
LinearLayout messageBody = new LinearLayout(getActivity());
View body = inflater.inflate(R.layout.messagebody, container);
messagesView.addView(body);
}
}
messagebody.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llMessageBody"
android:layout_width="fill_parent"
android:layout_margin="5dp"
android:layout_height="200dp"
android:background="#353535"
android:orientation="vertical" >
<TextView
android:id="#+id/tvMSBodyFrom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Research Station:"
android:textColor="#FFFFAA"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/tomatohigh"
/>
</LinearLayout>
message_detail.xml
<?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:background="#d3d6da"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#FFAA00" >
<TextView
android:id="#+id/tvMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:text="Select a Message:"
android:textColor="#353535"
android:textSize="30dp" />
</LinearLayout>
<ScrollView
android:id="#+id/svMessageDetail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#9900AA"
android:minHeight="300dp" >
<LinearLayout
android:id="#+id/llMessageDetail"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="wrap_content" >
</LinearLayout>
</ScrollView>
</LinearLayout>
The final implementaion would see me loop through a list of messages and add the a view with the message_body layout and change each part of the layout to the correct values of each message
Any ideas how to achieve this?
You can do like this:
YourView varView = new YourView(this);
myButton.setLayoutParams(new YourLayout.LayoutParams());
yourParentLayout.addView(varView);
Example: Add a button in parent linear layout
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
myLayout.addView(myButton);

Categories