Why ListView onClick does not work? - android

Trying to implement a onlick functionality for the android listview but something seems to not working. I tried to find some solutions over the internet and I found that there were recommendation to change the focusable property of imageview and textview elements. Tried it and it did not work. Appreciate if you guys can recommend any other alternatives.
Layout item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:id="#+id/rootItemId"
android:clickable="true"
android:gravity="center_vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable='false'
android:background="#drawable/frame">
<ImageView
android:id="#+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:contentDescription="#string/hello_world"
android:padding="5dp"
android:focusable='false'
android:src="#drawable/ic_launcher"
android:scaleType="fitXY"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:focusable='false'
android:layout_toRightOf="#id/ivIcon">
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable='false'
android:textAppearance="#android:style/TextAppearance.Medium"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
list fragment
public class EventsListFragment extends ListFragment{
ArrayList<Event> eventsChildren;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.e("RedditListingsClick",position + " " + id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
eventsChildren = new ArrayList<Event>();
EventsChildAdapter adapter = new EventsChildAdapter(inflater.getContext(), eventsChildren);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
list adapter
public class EventsChildAdapter extends ArrayAdapter<Event> {
Context context;
RelativeLayout root;
private static class ViewHolder {
TextView title;
ImageView thumbnail;
}
public EventsChildAdapter(Context context, ArrayList<Event> eventsChildren) {
super(context, R.layout.item_listing, eventsChildren);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event child = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_listing, null);
//root=(RelativeLayout)convertView.findViewById(R.id.rootItemId);
viewHolder.title = (TextView) convertView.findViewById(R.id.tvTitle);
//viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.ivIcon);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
System.out.println(child.getTitle());
viewHolder.title.setText(child.getTitle());
Picasso.with(this.context).load(child.getThumbnailImageURL()).resize(200, 100).into(viewHolder.thumbnail);
// Return the completed view to render on screen
return convertView;
}
}
In addition to the above, I have already tried adding android:descendantFocusability="blocksDescendants" to relativelayout but still did not work. Finally I tried to make the root relativelayout clickable and removed focus from the other elements and this did not work either.

You can try this:
public class EventsListFragment extends ListFragment implement OnItemClickListener {
...
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// the child callback here.
}
}
and this in onActivityCreated
setListAdapter(Your adapter);
getListView().setOnItemClickListener(this);

Related

Spinner setOnItemSelectedListener not working with custom adapter

I have made a custom spinner to populate a list of image and text that comes from mysql DB
when I tried to select an item from the spinner it doesn't work, even when I debug and put a break point inside the listener it doesn't go in.
My Adapter:
public class SpinnerShopAdapter extends ArrayAdapter<supermarketspinnerGS> {
private Context mcontext;
ArrayList<supermarketspinnerGS> SavedListContent;
public SpinnerShopAdapter(Context context, ArrayList<supermarketspinnerGS> SavedListContent) {
super(context, 0, SavedListContent);
this.mcontext = context;
this.SavedListContent = SavedListContent;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_supermarket_row, parent, false
);
}
ImageView imvSupermaket = convertView.findViewById(R.id.spinner_supermarket_imageView);
TextView tvSupamrketname = convertView.findViewById(R.id.spinner_supermarket_name);
TextView tvIdShop = convertView.findViewById(R.id.spinner_supermarket_idshop);
supermarketspinnerGS currentItem = getItem(position);
if (currentItem != null) {
Glide.with(context).load(currentItem.getImage()).into(imvSupermaket);
tvSupamrketname.setText(currentItem.getName());
tvIdShop.setText(currentItem.getIdshop());
}
return convertView;
}
}
onCreate code:
spinnerStore = (Spinner) findViewById(R.id.saveditemlist_spinner_storeshead);
adapterHead = new SpinnerShopAdapter(ActivitySavedListItem.this, getListHeadArray);
spinnerStore.setAdapter(adapterHead);
spinnerStore.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
supermarketspinnerGS clickedItem = (supermarketspinnerGS) parent.getItemAtPosition(position);
String clickedshopName = clickedItem.getIdshop();
selectedItemText=getListHeadArray.get(spinnerStore.getSelectedItemPosition()).getIdshop();
Toast.makeText(ActivitySavedListItem.this, clickedshopName + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I really don't know what is wrong and looking forward for your help. If you need more details please feel free to ask me I'll be glad to update my post
EDIT :
XML SPINNER
<LinearLayout
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:background="#drawable/spinner_market_shape"
app:layout_constraintStart_toEndOf="#+id/textView13"
app:layout_constraintTop_toBottomOf="#+id/textView10">
<Spinner
android:id="#+id/saveditemlist_spinner_storeshead"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp" />
</LinearLayout>
spinner_supermarket_row.xml
<RelativeLayout 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="wrap_content">
<ImageView
android:id="#+id/spinner_supermarket_imageView"
android:layout_width="75dp"
android:layout_height="25dp"
android:layout_marginStart="4dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:clickable="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/spinner_supermarket_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:visibility="invisible"
/>
<TextView
android:id="#+id/spinner_supermarket_idshop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:visibility="invisible"
/>
</RelativeLayout >
try to to add clickable=false to all your elements on your xml spinner row
Iam not sure but
I think you must set your spinner item click listener in your spinner custom adapter in initView function
like this:
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_supermarket_row, parent, false
);
}
ImageView imvSupermaket = convertView.findViewById(R.id.spinner_supermarket_imageView);
TextView tvSupamrketname = convertView.findViewById(R.id.spinner_supermarket_name);
TextView tvIdShop = convertView.findViewById(R.id.spinner_supermarket_idshop);
supermarketspinnerGS currentItem = getItem(position);
if (currentItem != null) {
Glide.with(context).load(currentItem.getImage()).into(imvSupermaket);
tvSupamrketname.setText(currentItem.getName());
tvIdShop.setText(currentItem.getIdshop());
}
parent.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(position==CUSTOM_POSITION){ /*do something*/}
}
});
return convertView;
}
I hope it works

Inflated Views inside a ListView are not visible

I'm trying to create a inflated dialog which contains dynamic amount of items.
These Items I inflate aswell.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int anzJobViews = getArguments().getInt("param");
View rootView = inflater.inflate(R.layout.dialog_job_chooser, container, false);
//getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
ListView listview = (ListView) rootView.findViewById(R.id.dialog_chooser_listview);
for (int i = 0; i < anzJobViews; i++) {
listview.addFooterView( new JobItemView(context));
Log.i("JobChooser","Item added");
}
return rootView;
}
The View (Contains some simple TextViews)
private void init() {
inflate(getContext(), R.layout.job_item_view, this);
}
When showing the dialog I see Nothing.
The xml layout for the dialog.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:background="#drawable/round_corners_selected"
android:backgroundTint="#color/washedOutGreen">
<ListView
android:id="#+id/dialog_chooser_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
The Items a want to add to the List.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/blue_focused">
<TextView
android:id="#+id/tv_jobname_area"
android:text="defaultName"
android:layout_margin="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_jobvalue_area"
android:text="0 /h"
android:layout_margin="5dp"
android:layout_toRightOf="#+id/tv_jobname_area"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Why don't use an adapter to populate your listview? An example from here: http://www.pcsalt.com/android/listview-using-baseadapter-android/
public MyBaseAdapter(Context context, ArrayList myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
mViewHolder.tvDesc.setText(currentListData.getDescription());
mViewHolder.ivIcon.setImageResource(currentListData.getImgResId());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
tvDesc = (TextView) item.findViewById(R.id.tvDesc);
ivIcon = (ImageView) item.findViewById(R.id.ivIcon);
}
}
}
Also, if you are in a pre kitkat enviroment, you can only use addFooterView before setting the adapter.
Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.
Reference: http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)
use getView function to setup your listview
public View getView (int position, View convertView, ViewGroup list) {
View element;
if (convertView == null) {
element = View.inflate(context, R.layout.items, null);
}
else {
element = convertView;
}
//setup here something
//e.g.
TextView tv = (TextView) v.findViewById(R.id.tv);
tv.setText("myText");
return element;
}

Android Listview item Partially Visible

i created a custom Listview Adapter with ViewHolder and used it with a ListFragment, for some reason i dont know, the last Listview item does not render totally
Adapter Code
public class ListViewAdapter extends ArrayAdapter<ListItem> {
public ListViewAdapter(Context context, List<ListItem> items) {
super(context, R.layout.row, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListItem item = getItem(position);
if(item!=null){
viewHolder.ivIcon.setImageDrawable(item.icon);
viewHolder.tvTitle.setText(item.title);
viewHolder.tvDescription.setText(item.description);
}
return convertView;
}
/**
* The view holder design pattern prevents using findViewById()
* repeatedly in the getView() method of the adapter.
*
* #see http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder
*/
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDescription;
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_vertical"
android:background="#color/frame_background"
android:padding="5dp" >
<!-- the innner view - provides the white rectangle -->
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/frame" >
<!-- the icon view -->
<ImageView android:id="#+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:contentDescription="desc"
android:scaleType="fitXY"
android:layout_alignParentLeft="true"
android:src="#mipmap/ic_launcher" />
<!-- the container view for the title and description -->
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/ivIcon"
android:layout_centerVertical="true" >
<!-- the title view -->
<TextView android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#android:style/TextAppearance.Medium" />
<!-- the description view -->
<TextView android:id="#+id/tvDescription"
android:layout_below="#id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#android:style/TextAppearance.Small"
android:padding="3dp" />
</RelativeLayout>
</RelativeLayout>
And the Fragment code since i am using a ListFragment
Public class IntroFragment extends ListFragment {
private List<ListItem> mItems; // ListView items list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize the items list
mItems = new ArrayList<ListItem>();
Resources resources = getResources();
String[] factfiles=resources.getStringArray(R.array.SunFacts);
mItems.add(new ListItem(resources.getDrawable(R.mipmap.ic_launcher), factfiles[i], factfiles[i])); }
// initialize and set the list adapter
setListAdapter(new ListViewAdapter(getActivity(), mItems));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
getListView().setDivider(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// retrieve theListView item
ListItem item = mItems.get(position);
// do something
Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
}
}
the Screenshot below shows what i mean,notice the white edge of a new Listview item at the bottom,
and the listview will not scroll anymore.
Screenshot (cant upload it here due to rep points)
Thanks in advance..this is already driving me half bean and bananas..

listview item cannot be click in android

i have created Custom listview and i add a onclick listener to it but it was not working.the below is my code
This is my MainActivity Class:
public class MainActivity extends Activity {
public boolean[] status;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// Attach the adapter to a ListView
listView = (ListView) findViewById(R.id.lvUsers);
populateUsersList();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
Toast.makeText(getBaseContext(),"Hello", Toast.LENGTH_SHORT).show();
}
});
}
private void populateUsersList() {
// Construct the data source
ArrayList<User> arrayOfUsers = User.getUsers();
// Create the adapter to convert the array to views
CustomUsersAdapter adapter = new CustomUsersAdapter(this, arrayOfUsers);
listView.setAdapter(adapter);
}
}
this is my adapter class:
public class CustomUsersAdapter extends ArrayAdapter<User> {
public CustomUsersAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
// Return the completed view to render on screen
return convertView;
}
}
i want to get the value from listview when the appropriate toggle button is checked .and want to save the value of toggle button and the appropriate text in arraylist.
this my xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvUsers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This is my second 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:padding="10dp"
>
<TextView
android:id="#+id/tvName"
android:layout_alignBaseline="#+id/ivUserIcon"
android:layout_toRightOf="#+id/ivUserIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="6dp"
android:text="Sarah"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvHometown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvName"
android:layout_below="#+id/tvName"
android:text="San Marco"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/tvName"
android:layout_marginRight="15dp"
android:text="ToggleButton" />
</RelativeLayout>
Change your RelativeLayout to
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:descendantFocusability="blocksDescendants"
>
This view will block any of its descendants from getting focus, even if they are focusable.
You must set the button on clicklistener.
tgbtn.setOnClickListener(new OnClickListener(position));
Dont know it it works but try anything like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
tgbtn.setOnClickListener(new OnButtonClickListener(position));
// Return the completed view to render on screen
return convertView;
}
then a class for the ButtonClick:
private class OnButtonClickListener implements OnClickListener {
int _postion;
// constructor
public OnButtonClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
}
}
below of your code that there is a ListView and you wanna able clicked function to the list item, write this code.
public void onListItemClick(ListView parent, View v, int position, long id){
// do something here
// Example below make a toast message
Toast.makeText(getApplicationContext(), "I clicked item of list number " + position,Toast.LENGTH_SHORT).show();
}

findViewByID returning null on BaseAdapter

I started using fragments to develop a new app, one of the fragments is a ListFragment,
when I use the adapter I made to show the list's rows I get some null from some findViewById that I use on the getView() method.
The structure is:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/fragment_container">
</FrameLayout>
</RelativeLayout>
frag_detail.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list"
android:layout_gravity="center"/>
</LinearLayout>
detail_list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/detailItemLayout" >
<ImageButton
android:layout_width="64dp"
android:layout_height="64dp"
android:id="#+id/imgIcon"
android:layout_below="#+id/txtTitle"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="txtTitle"
android:id="#+id/txtTitle"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="label1"
android:id="#+id/label1"
android:layout_below="#+id/imgIcon"
android:layout_alignParentLeft="true"/>
</RelativeLayout>
DetailFragment class
public class DetailFragment extends ListFragment {
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_detail,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MonsterDataSource ds = new MonsterDataSource(context);
List<Monster> lsMonster = ds.getAllMonsters();
//ListView lsView = (ListView)this.getActivity().findViewById(R.id.lsDetail);
MonsterListAdapter adapter = new MonsterListAdapter(context,lsMonster);
//lsView.setAdapter(adapter);
setListAdapter(adapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity.getApplicationContext();
}
}
And the MonsterListAdapter class
public class MonsterListAdapter extends BaseAdapter {
static class ViewHolder {
private TextView txtTitle;
private ImageView imgIcon;
private TextView txtHealth;
}
private Context context;
private LayoutInflater inflater;
private List<Monster> data;
private ViewHolder holder;
public MonsterListAdapter(Context c, List<Monster> data){
context = c;
this.data = data;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/*Basic BaseAdapter Methods*/
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(R.layout.menu_list_item, null);
holder = new ViewHolder();
/*Those Guys get null*/
RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.detailItemLayout);
holder.txtTitle = (TextView) view.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView) view.findViewById(R.id.imgIcon);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Monster monster = data.get(i);
holder.txtTitle.setText(monster.name);
holder.imgIcon.setImageResource(monster.imgResID);
holder.txtHealth.setText(monster.health);
return view;
}
}
In case anyone asking, I'm trying to retrieve the relative layout to add some controls dynamically after.
Thanks
You posted the XML for detail_list_item.xml but in your code you inflate menu_list_item.xml.
detail_list_item.xml contains all of the IDs you are trying to find so it appears you have accidentally inflated the wrong View in getView
Additionally, you should remove your ViewHolder as a member variable and place it as a local variable in the getView method. You are reusing that variable for multiple views at the same time which means you have the potential for modifying the wrong views at different positions (data going to the wrong positions, etc).
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
...
...//all of your other code here
}
Try without affecting "view"
RelativeLayout layout = (RelativeLayout)findViewById(R.id.detailItemLayout);
holder.txtTitle = (TextView) findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView) findViewById(R.id.imgIcon);
Edit This works for me... My texviews nbCommentaires and Comment give NullPointerException if i inflate View to them... I thought you get the same issue...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.comment_row, null);
}
v.setTag(position);
Commentaires o = Global_reco.CommRecos.get(position);
if (o != null) {
TextView nom = (TextView) v.findViewById(R.id.nom_com);
TextView com = (TextView) v.findViewById(R.id.com);
ImageView photo = (ImageView) v.findViewById(R.id.profile_com);
TextView nbCommentaires = (TextView) findViewById(R.id.nb_commentaires);
TextView Comment = (TextView)findViewById(R.id.nbre_comment);
photo.setTag(position);

Categories

Resources