i created custom listview with text and two buttons, i set up arraylist and adapter but my listview is showing every element as last, for ex. if i add 3 elements: "text1","text2","text3" my listview shows "text3", "text3" "text3" and i dont have any idea why.
private ListView lista;
private List<Piosenka> listaPiosenek;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
lista = (ListView) findViewById(R.id.listView1);
lista.setClickable(true);
}
public void update_listy() throws MalformedURLException, IOException
{
final List<Piosenka> listaPiosenek = new ArrayList<Piosenka>();
listaPiosenek.add(new Piosenka("text1"));
listaPiosenek.add(new Piosenka("text2"));
listaPiosenek.add(new Piosenka("text3"));
PiosenkaAdapter adapter = new PiosenkaAdapter(this, listaPiosenek);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long index)
{
System.out.println("sadsfsf");
}
});
lista.setAdapter(adapter);
}
Edit: PiosenkaAdapter code
public class PiosenkaAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Piosenka> listapiosenek;
public PiosenkaAdapter(Context context, List<Piosenka> listapiosenek) {
this.context = context;
this.listapiosenek = listapiosenek;
}
public int getCount() {
return listapiosenek.size();
}
public Object getItem(int position) {
return listapiosenek.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Piosenka element = listapiosenek.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_element, null);
}
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Button btnPobierz = (Button) convertView.findViewById(R.id.btnPobierz);
btnPobierz.setFocusableInTouchMode(false);
btnPobierz.setFocusable(false);
btnPobierz.setTag(element);
Button btnPlay = (Button) convertView.findViewById(R.id.btnPlay);
btnPlay.setFocusableInTouchMode(false);
btnPlay.setFocusable(false);
btnPlay.setOnClickListener(this);
btnPlay.setTag(element);
// btnRemove.setId(position);
return convertView;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPobierz:
Piosenka entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
case R.id.btnPlay:
entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
}
}
}
Try this...
lista.setAdapter(adapter);
adapter.notifyDataSetChanged();
Can you paste you PiosenkaAdapter's code?
I don't know your language, but the Piosenka variable is fetched correctly in getView()
Piosenka element = listapiosenek.get(position);
But this looks strange to me
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Piosenka.getTytul() looks to me as a static method call, where you should do a regular method call to element.getTytul() instead.
Related
Here's the Adapter source code which extends BaseAdapter and contains multiple views.
public class AddNewAlarmOptionItemListAdapter extends BaseAdapter {
private static final int ITEM_TEXT_ONLY = 0;
private static final int ITEM_TEXT_AND_PROGRESS_BAR = 1;
private static final int ITEM_TEXT_AND_SWITCH = 2;
// number of types in total.
private static final int ITEM_TOTAL_TYPES = 3;
private ArrayList<AddNewAlarmOptionItem> itemLists = new ArrayList<>();
public AddNewAlarmOptionItemListAdapter() {
}
// overridden method for enabling the adapter to contain different types of views.
#Override
public int getViewTypeCount() {
return ITEM_TOTAL_TYPES;
}
// overridden method for enabling the adapter to contain different types of views.
#Override
public int getItemViewType(int position) {
return itemLists.get(position).getType();
}
#Override
public int getCount() {
return itemLists.size();
}
#Override
public Object getItem(int position) {
return itemLists.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final Context context = viewGroup.getContext();
int viewType = getItemViewType(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AddNewAlarmOptionItem item = itemLists.get(position);
switch(viewType) {
case ITEM_TEXT_ONLY:
convertView = inflater.inflate(R.layout.listitem_text_only, viewGroup, false);
TextView tvSubject = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvOptions = (TextView) convertView.findViewById(R.id.tvSubtitle);
tvSubject.setText(item.getTitle());
tvOptions.setText(item.getSubtitle());
break;
case ITEM_TEXT_AND_PROGRESS_BAR:
convertView = inflater.inflate(R.layout.listitem_text_and_seek_bar, viewGroup, false);
TextView tvAlarmType = (TextView) convertView.findViewById(R.id.tvAlarmType);
TextView tvAlarmOption = (TextView) convertView.findViewById(R.id.tvAlarmOption);
tvAlarmType.setText(item.getTitle());
tvAlarmOption.setText(item.getSubtitle());
ImageView ivSpeaker = (ImageView) convertView.findViewById(R.id.ivSpeaker);
SeekBar sbVolume = (SeekBar) convertView.findViewById(R.id.sbVolume);
break;
case ITEM_TEXT_AND_SWITCH:
convertView = inflater.inflate(R.layout.listitem_text_and_switch, viewGroup, false);
TextAndSwitchItem textAndSwitchItem = new TextAndSwitchItem();
TextView tvAlarmOptionTitle = (TextView) convertView.findViewById(R.id.tvAlarmOptionTitle);
TextView tvAlarmOptionDescription = (TextView) convertView.findViewById(R.id.tvOptionDescription);
Switch switchOption = (Switch) convertView.findViewById(R.id.switchOption);
tvAlarmOptionTitle.setText(item.getTitle());
tvAlarmOptionDescription.setText(item.getSubtitle());
switchOption.setChecked(true);
break;
}
return convertView;
}
// add a text-only item to list view
public void addItem(TextOnlyItem item) {
item.setType(ITEM_TEXT_ONLY);
itemLists.add(item);
}
// add a text-and-progress-bar item to list view
public void addItem(TextAndSeekbarItem item) {
item.setType(ITEM_TEXT_AND_PROGRESS_BAR);
itemLists.add(item);
}
// add a text-and-switch item to list view
public void addItem(TextAndSwitchItem item) {
item.setType(ITEM_TEXT_AND_SWITCH);
itemLists.add(item);
}
}
And this is the part of an Activity which contains the list and the onItemClickListener.
listAdapter = new AddNewAlarmOptionItemListAdapter();
lvAlarmOptionList = (ListView) findViewById(R.id.lvAlarmOptionList);
lvAlarmOptionList.setAdapter(listAdapter);
tpTimePicker = (TimePicker) findViewById(R.id.tpTimePicker);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnSave = (Button) findViewById(R.id.btnSave);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cancelAddingNewAlarm();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveAlarm();
}
});
initializeListItems();
addItemsToListView();
lvAlarmOptionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(CreateNewAlarmActivity.this, position, Toast.LENGTH_SHORT).show();
}
});
When I ran this code, I expected that the Toast message would appear with the corresponding position number, but it crashed with this message - android.content.res.Resources$NotFoundException: String resource ID #0x0.
You should use
Toast.makeText(CreateNewAlarmActivity.this, ""+position, Toast.LENGTH_SHORT).show();
From your code, you are trying to toast the position of item click in listview.
But Toast accepts a message in String resource to display.
This is common mistake for most of the developers, will do for toast.
Toast.makeText has two versions
1st method will take context, resourceid -> Integer, duration
Toast.makeText(context, resource, Toast.LENGTH_SHORT).show();
2nd method will take context, string message, duration
Toast.makeText(context, resource, Toast.LENGTH_SHORT).show();
In your case your passing position, so it will call 1st method, it will look for any resource with id 0, that will not found so it will throw Resources$NotFoundException.
Solution:
Toast.makeText(context, string.valueof(resource), Toast.LENGTH_SHORT).show();
lvAlarmOptionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(CreateNewAlarmActivity.this, position+"", Toast.LENGTH_SHORT).show();
}
});
Am trying to update my listview on every selection of the spinner. but its not working. Instead of getting new data, listview is repeating the same values.
I am unable to find out what is my mistake.
here is my avtivity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_performance_details);
PerfList = new ArrayList<PerformanceListItem>();
months = (Spinner) findViewById(R.id.load_month);
listview_performance = (ListView) findViewById(R.id.performance_details_list);
sadapter = new PerformanceAdapter(PerformanceDetails.this, PerfList);
months.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner a=(Spinner)parent;
if(a.getId() == R.id.load_month) {
monthid =1+(int)months.getSelectedItemPosition();
Toast.makeText(getApplicationContext(),""+monthid,Toast.LENGTH_LONG).show();
new setAsyncTask_performance().execute();
}
}
after selecting spinner data it is sent to server and from server its relevant data is fetched and sent back to the list view. now when i first time select the spinner it show the data accordingly. But on second selection it will include the previous data without updating the listview
Adapter Code:
public class PerformanceAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private Context context;
private List<PerformanceListItem> performanceList;
public PerformanceAdapter(Activity activity, List<PerformanceListItem> PList) {
this.activity = activity;
this.performanceList = PList;
}
#Override
public int getCount() {
return performanceList.size();
}
#Override
public Object getItem(int position) {
return performanceList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.performance_itemlist, null);
}
Animation slideUp = AnimationUtils.loadAnimation(activity, R.anim.slide_up);
TextView staffName = (TextView) convertView.findViewById(R.id.perf_staffName);
TextView staffDesignation = (TextView) convertView.findViewById(R.id.perf_Design);
TextView staffPerformance = (TextView) convertView.findViewById(R.id.perf_performance);
PerformanceListItem plist = performanceList.get(position);
staffName.setText(plist.getpStaffName());
staffDesignation.setText(plist.getpDesignation());
staffPerformance.setText(plist.getpPerformance());
slideUp.setDuration(500);
convertView.startAnimation(slideUp);
slideUp = null;
return convertView;
}
}
and this is my performance list to get and set data
PerformanceListItems code:
public class PerformanceListItem {
private String pSid;
private String pStaffName;
private String pDesignation;
private String pPerformance;
private String pList;
public PerformanceListItem(){
}
public PerformanceListItem(String pList){
this.pList = pList;
}
public String getpSid(){
return pSid;
}
public void setpSid(String pSid){
this.pSid = pSid;
}
public String getpStaffName(){
return pStaffName;
}
public void setpStaffName(String pStaffName){
this.pStaffName = pStaffName;
}
public String getpDesignation(){
return pDesignation;
}
public void setpDesignation(String pDesignation){
this.pDesignation = pDesignation;
}
public String getpPerformance(){
return pPerformance;
}
public void setpPerformance(String pPerformance){
this.pPerformance = pPerformance;
}
}
After debugging the entire code i found that my JSONObject is not updating with new value
any help would be appreciable.
Update the data of your adapter when you execute this
new setAsyncTask_performance().execute();
If you want to show only the new data just remove all your listview items then update the data and set the adapter again.
dont set adapter in oncreate. Set your adapter in Asynctask Post execute. and set your array inside doinbackground along with getting data task.
I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}
Please tell me how to add items in listview arrayadapter?
I found only how to make for standard adapter
Activity:
public class Activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.m);
ListView lv=(ListView) findViewById(R.id.lv);
String[] Id1={"1","2","3"}, Text1={"one","two","three"};
CustomAdapter ad = new CustomAdapter(this, Id1 , Text1);
ad.setCustomListener(new LVListener() {
public void onClick(String text) {
Log.d("APP", text);
}
});
lv.setAdapter(ad);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setVisibility(View.GONE);
String[] Id2={"4","5","6"},Text2={"four","five","six"};
// add Id2 and Text2 in listview
}
});
}
}
CustomAdapter:
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] id, text;
private ListViewListener micl;
public CustomAdapter(Context context, String[] id, String[] text) {
super(context, R.layout.list, id);
this.context = context;
this.id = id;
this.text = text;
}
public void setCustomListener(ListViewListener micl) { this.micl = micl; }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View View = inflater.inflate(R.layout.list, parent, false);
final int pos = position;
final TextView tView = (TextView) View.findViewById(R.id.textView);
tView.setText(text[pos]);
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (micl != null)
micl.onClick(text[pos]);
}
});
return View;
}
}
I tried to do with notifyDatasetChanged() but nothing happened.
Please tell me how to do that.
ArrayAdapter has the add method, but in order to use it the dataset you provide to the super can not be an array, that's because the using Arrays.asList(objects), that returns an immutable list. From the documentation
Returns a List of the objects in the specified array. The size of the
List cannot be modified, i.e. adding and removing are unsupported, but
the elements can be set. Setting an element modifies the underlying
array.
I'm trying to make a ListFragment. I looked the Api Demo (FragmentLayout). it works on a simple example and now i want to apply it to my existing project.
Here is my code. I create inner classes (RecipeList & RecipeDetail) as in the Api Demo.
public class InfoActivity extends MenuActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_fragment_layout);
// ...
}
public static class RecipeList extends ListFragment {
private int mCurrentSelectedItemIndex = -1;
private boolean mIsTablet = false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
accountData = new ArrayList<Account>();
new AccountSyncTask() {
#Override
public void onPostExecute(
final ArrayList<ArrayList<String>> result) {
// For each retrieved account
Bd.insert(retrievedAccount);
accountData.add(retrievedAccount);
}
accountListAdapter = new AccountListAdapter(
InfoActivity.this, R.layout.accountlist_detail,
accountData);
accountListAdapter = new AccountListAdapter(
activityContext, R.layout.accountlist_detail,
accountData);
setListAdapter(accountListAdapter);
}
}.execute(sessionName, null, "getAllObjectOnServer",
String.valueOf(nbRow));
if (savedInstanceState != null) {
mCurrentSelectedItemIndex = savedInstanceState.getInt(
"currentListIndex", -1);
}
// This is a tablet if this view exists
View recipeDetails = getActivity()
.findViewById(R.id.recipe_details);
mIsTablet = recipeDetails != null
&& recipeDetails.getVisibility() == View.VISIBLE;
if (mIsTablet) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mIsTablet && mCurrentSelectedItemIndex != -1) {
showRecipeDetails();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
mCurrentSelectedItemIndex = position;
showRecipeDetails();
}
private void showRecipeDetails() {
if (mIsTablet) {
// Set the list item as checked
getListView().setItemChecked(mCurrentSelectedItemIndex, true);
// Get the fragment instance
RecipeDetail details = (RecipeDetail) getFragmentManager()
.findFragmentById(R.id.recipe_details);
// Is the current visible recipe the same as the clicked? If so,
// there is no need to update
if (details == null
|| details.getRecipeIndex() != mCurrentSelectedItemIndex) {
details = RecipeDetail
.newInstance(mCurrentSelectedItemIndex);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.recipe_details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentListIndex", mCurrentSelectedItemIndex);
}
}
public static class RecipeDetail extends Fragment {
private int mRecipeIndex;
public static RecipeDetail newInstance(int recipeIndex) {
// Create a new fragment instance
RecipeDetail detail = new RecipeDetail();
// Set the recipe index
detail.setRecipeIndex(recipeIndex);
return detail;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater
.inflate(R.layout.recipe_details, container, false);
//..
return v;
}
public int getRecipeIndex() {
return mRecipeIndex;
}
public void setRecipeIndex(int index) {
mRecipeIndex = index;
}
}
I have a custom ArrayAdapter (my items in the ListFragment contain 4 textViews and a clickable imageButton).
AccountListAdapter :
public class AccountListAdapter extends ArrayAdapter<Account> {
private final Context context;
private final int layoutResourceId;
private final ArrayList<Account> data;
public AccountListAdapter(Context context, int layoutResourceId,
ArrayList<Account> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
AccountHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
holder = new AccountHolder();
convertView.setClickable(true);
convertView.setFocusable(true);
holder.txtName = (TextView) convertView.findViewById(R.id.nom);
holder.txtId = (TextView) convertView.findViewById(R.id.id);
convertView.setTag(holder);
} else {
holder = (AccountHolder) convertView.getTag();
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click", "index = " + position);
}
});
holder.txtName.setText(data.get(position).getName());
holder.txtId.setText(data.get(position).getId());
convertView.setBackgroundResource(R.drawable.list_selector);
ImageButton img = (ImageButton) convertView.findViewById(R.id.check);
img.setTag(position);
return convertView;
}
static class AccountHolder {
TextView txtName;
TextView txtId;
}
}
Problem :
When i click on an Item of the listFragment,
public void onListItemClick(ListView l, View v, int position, long id) {
mCurrentSelectedItemIndex = position;
Log.i("click", "here";
showRecipeDetails();
}
is not called but the listener on an item defined in AccountListAdapter works
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click", "index = " + position);
}
});
Why is onListitemClick never called ?
Another question : is it a proper way to consume a web service in another thread in the onActivityCreated function of my ListFragment (in order to populate the list) ?
Thx in advance
EDIT = For the moment i made "showRecipeDetails" static and call it in the listener in my custom ArrayAdapter.
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RecipeList.showRecipeDetails(position);
}}
I'm not satisfied with my solution, i'm interessed to any other solution
OnItemClickListeners must first be associated with the ListView you want to record clicks for. In your onActivityCreated(..) method, place getListView().setOnItemClickListener(this) somewhere and put implements OnItemClickListener after public static class RecipeList extends ListFragment.