I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!
Related
I am just starting to work with dialog fragment and there is a lot that I don't know. I have a MainActivity that by clicking on a button opens a DialogFragment, in that DialogFragment I have another button that opens a SecondDialogFragment. The first one works fine but the second one not, I click on the button in the first DialogFragment the screen lose focus with the background but shows nothing. I really don't know what is wrong? I would be grateful if someone could give me a hand.
This is the first DialogFragment where I call the second one by onClick.
DialogFragment.java
ImageButton iconButton = v.findViewById(R.id.user_icon);
iconButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DSelectIcon().show(getFragmentManager(), "DSelectIcon");
}
});
SecondDialogFragment.java
public class DSelectIcon extends DialogFragment{
private View v = null;
private ImageView Selection;
private static final Integer[] items = { R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1 };
public DSelectIcon() {
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Restore last state for checked position.
}
LayoutInflater inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.grid_icon_event, null);
return createDSelectIcon(v);
}
private AlertDialog createDSelectIcon(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Selection = v.findViewById(R.id.selection);
GridView grid = v.findViewById(R.id.grid);
// grid.setAdapter(new ArrayAdapter<Integer>(this, R.layout.cell,
// items));
grid.setAdapter(new CustomGridAdapter((MainActivity)getActivity(), items));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked postion is" + i,
Toast.LENGTH_LONG).show();
//Selection.setImageResource(items[arg2]);
}
});
return builder.create();
}
public class CustomGridAdapter extends BaseAdapter {
private Activity mContext;
// Keep all Images in array
public Integer[] mThumbIds;
// Constructor
public CustomGridAdapter(MainActivity mainActivity, Integer[] items) {
this.mContext = mainActivity;
this.mThumbIds = items;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
}
Grid_icon_event.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".MainActivity" >
<ImageView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="100dip"
android:gravity="center"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="40dip" >
</GridView>
</LinearLayout>
FIXED!!!
A stupid mistake, but I forgot to add this:
builder.setView(v);
In the SecondDialogFragment.java method createDSelectIcon
Now it looks like this:
public class DSelectIcon extends DialogFragment{
private View v = null;
private ImageView Selection;
private static final Integer[] items = { R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1 };
public DSelectIcon() {
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Restore last state for checked position.
}
LayoutInflater inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.grid_icon_event, null);
return createDSelectIcon(v);
}
private AlertDialog createDSelectIcon(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Selection = v.findViewById(R.id.selection);
GridView grid = v.findViewById(R.id.grid);
// grid.setAdapter(new ArrayAdapter<Integer>(this, R.layout.cell,
// items));
grid.setAdapter(new CustomGridAdapter((MainActivity)getActivity(), items));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked postion is" + i,
Toast.LENGTH_LONG).show();
//Selection.setImageResource(items[arg2]);
}
});
builder.setView(v);
return builder.create();
}
public class CustomGridAdapter extends BaseAdapter {
private Activity mContext;
// Keep all Images in array
public Integer[] mThumbIds;
// Constructor
public CustomGridAdapter(MainActivity mainActivity, Integer[] items) {
this.mContext = mainActivity;
this.mThumbIds = items;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
}
Image
I have an EditText which adds items to this RecyclerView and to the Realm DB. That works fine. The problem is that I don't know how to remove those items from both the RecyclerView and from the Realm DB. Should this be done on the Fragment or on the adapter? And how? Thanks!
There is an image on top showing a screenshot of the app.
Here is the Fragment where the RecyclerView is:
public class FragmentMyList extends Fragment{
private RecyclerView recyclerView;
private EditText editTxt;
private FloatingActionButton btn;
private Item item;
private ArrayList<Item> itemList;
private AdapterItemsRecycler adapterItemsRecycler;
private Realm realm;
RealmResults<Item> results;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View vistaADevolver = inflater.inflate(R.layout.fragment_my_list, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Realm.init(getContext());
realm = Realm.getDefaultInstance();
editTxt = (EditText)vistaADevolver.findViewById(R.id.editText);
btn = (FloatingActionButton) vistaADevolver.findViewById(R.id.button);
recyclerView = (RecyclerView) vistaADevolver.findViewById(R.id.recyclerViewToDo);
itemList = new ArrayList<>();
results = realm.where(Item.class).equalTo("id", 1).findAll();
final InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
adapterItemsRecycler = new AdapterItemsRecycler(results, getActivity(), new ItemsListener());
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new SimpleItemDivider(getActivity()));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapterItemsRecycler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemName = editTxt.getText().toString();
saveIntoDatabase(itemName);
inputManager.hideSoftInputFromWindow(getView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
editTxt.getText().clear();
adapterItemsRecycler.notifyDataSetChanged();
}
});
return vistaADevolver;
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
private void saveIntoDatabase(final String itemName) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
item = bgRealm.createObject(Item.class);
item.setName(itemName);
item.setPoint(itemName);
item.setId(1);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("POINT", item.getPoint());
fragment.setArguments(bundle);
itemList.add(item);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
Log.v("database", "Stored ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
Log.e("database", error.getMessage());
}
});
}
class ItemsListener implements AdapterView.OnClickListener{
#Override
public void onClick(View view) {
Item itemTouched = results.get(recyclerView.getChildAdapterPosition(view));
EscuchadorInterface unEscuchador = (EscuchadorInterface)getActivity();
unEscuchador.itemSelected(itemTouched);
}
}
public interface EscuchadorInterface{
public void itemSelected(Item anItem);
}
}
My RecyclerView adapter:
public class AdapterItemsRecycler extends RecyclerView.Adapter {
private RealmResults<Item> itemList;
private Context context;
private View.OnClickListener listener;
private Realm realm;
public AdapterItemsRecycler(RealmResults<Item> itemList, Context context, View.OnClickListener listener) {
this.itemList = itemList;
this.context = context;
this.listener = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_list_detail, parent, false);
view.setOnClickListener(listener);
ItemViewHolder itemViewHolder = new ItemViewHolder(view);
return itemViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Item item = itemList.get(position);
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.loadItem(item);
}
#Override
public int getItemCount() {
return itemList.size();
}
private class ItemViewHolder extends RecyclerView.ViewHolder{
private TextView itemText;
private ImageButton imageButton;
public ItemViewHolder(View view) {
super(view);
itemText = (TextView) view.findViewById(R.id.textViewItemNameTD);
imageButton = (ImageButton) view.findViewById(R.id.delete);
}
public void loadItem(Item item) {
itemText.setText(item.getName());
imageButton.setImageResource(R.drawable.trash);
}
public ImageButton getImageButton() {
return imageButton;
}
}
}
RecyclerView's detail:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context="com.segunfamisa.sample.bottomnav.MainActivity">
<ImageButton
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tint="#03A9F4"
android:scaleType="centerInside"
android:background="#ffffff"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:onClick="deleteItem"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewItemNameTD"
android:textSize="14dp"
android:textColor="#212121"
android:background="#ffffff"
android:padding="10dp"
android:layout_toRightOf="#+id/delete"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:scaleType="centerInside"
android:background="#ffffff"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
Just use RealmRecyclerViewAdapter with the RealmResults directly, which handles synchronization between database and list and adapter automatically.
public class FragmentMyList
extends Fragment {
private RecyclerView recyclerView;
private EditText editTxt;
private FloatingActionButton btn;
private AdapterItemsRecycler adapterItemsRecycler;
private Realm realm;
RealmResults<Item> results;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View vistaADevolver = inflater.inflate(R.layout.fragment_my_list, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Realm.init(getContext());
realm = Realm.getDefaultInstance();
editTxt = (EditText) vistaADevolver.findViewById(R.id.editText);
btn = (FloatingActionButton) vistaADevolver.findViewById(R.id.button);
recyclerView = (RecyclerView) vistaADevolver.findViewById(R.id.recyclerViewToDo);
results = realm.where(Item.class).equalTo("id", 1).findAll();
final InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
adapterItemsRecycler = new AdapterItemsRecycler(results, new ItemsListener());
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new SimpleItemDivider(getActivity()));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapterItemsRecycler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemName = editTxt.getText().toString();
saveIntoDatabase(itemName);
inputManager.hideSoftInputFromWindow(getView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
editTxt.getText().clear();
}
});
return vistaADevolver;
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
private void saveIntoDatabase(final String itemName) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
Item item = bgRealm.createObject(Item.class);
item.setName(itemName);
item.setPoint(itemName);
item.setId(1);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
Log.v("database", "Stored ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
Log.e("database", error.getMessage());
}
});
}
class ItemsListener
implements AdapterView.OnClickListener {
#Override
public void onClick(View view) {
Item itemTouched = results.get(recyclerView.getChildAdapterPosition(view));
EscuchadorInterface unEscuchador = (EscuchadorInterface) getActivity();
unEscuchador.itemSelected(itemTouched);
}
}
public interface EscuchadorInterface {
public void itemSelected(Item anItem);
}
}
// compile 'io.realm:android-adapters:2.0.0'
public class AdapterItemsRecycler
extends RealmRecyclerViewAdapter<Item, ItemViewHolder> {
private View.OnClickListener listener;
public AdapterItemsRecycler(OrderedRealmCollection<Item> itemList, View.OnClickListener listener) {
super(itemList, true);
this.listener = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.my_list_detail, parent, false);
view.setOnClickListener(listener);
ItemViewHolder itemViewHolder = new ItemViewHolder(view);
return itemViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Item item = getData().get(position);
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.loadItem(item);
}
private static class ItemViewHolder
extends RecyclerView.ViewHolder {
private TextView itemText;
private ImageButton imageButton;
public ItemViewHolder(View view) {
super(view);
itemText = (TextView) view.findViewById(R.id.textViewItemNameTD);
imageButton = (ImageButton) view.findViewById(R.id.delete);
}
public void loadItem(Item item) {
itemText.setText(item.getName());
imageButton.setImageResource(R.drawable.trash);
}
public ImageButton getImageButton() {
return imageButton;
}
}
}
private void deleteFromDatabase(final String itemName) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
Item item = bgRealm.where(Item.class).equalTo("name", itemName).findFirst();
if(item != null) {
item.deleteFromRealm();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
Log.v("database", "Delete ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
Log.e("database", error.getMessage());
}
});
}
I have a fragment with a list of recipes. But I can't get the onItemClick to work...
I have tried it with onListItemClick but that didn't seem to work either.
My Fragment
public class RecipeBookListViewFragment extends ListFragment implements AdapterView.OnItemClickListener {
private List<Recipe> recipes;
private DataPassListener mCallback;
private ListView recipeList;
public interface DataPassListener{
public void passData(Recipe recipe);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
RecipeBookActivity.CONTEXT = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recipeitem_list, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fillRecipeBook();
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Recipe recipe = (Recipe) getListAdapter().getItem(position);
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "halloooooo...");
mCallback.passData(recipe);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
recipeList = getListView();
recipeList.setClickable(true);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try {
mCallback = (DataPassListener)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
private void fillRecipeBook(){
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "loading...");
RestClient.ApiInterface service = RestClient.getClient();
Call<List<Recipe>> call = service.recipes();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Response<List<Recipe>> response, Retrofit retrofit) {
dialog.dismiss();
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
recipes = response.body();
ArrayAdapter<String> adapter = new RecipeListAdapter(getActivity(), recipes);
setListAdapter(adapter);
} else {
// response received but request not successful (like 400,401,403 etc)
//Handle errors
}
}
#Override
public void onFailure(Throwable t) {
Log.d("MainActivity", "GOE KAPOT " + t.getMessage());
dialog.dismiss();
}
});
}
}
my ListView.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView android:id="#android:id/list" android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#FFCC00"
android:dividerHeight="2dp"/>
<TextView android:id="#+id/recipe_title" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="left"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
My custom adapter
public class RecipeListAdapter extends ArrayAdapter{
private Context context;
private boolean useList = true;
private List<Recipe> recipes;
public RecipeListAdapter(Context context, List<Recipe> recipes) {
super(context,-1, recipes);
this.context = context;
this.recipes = recipes;
}
private class ViewHolder{
TextView titleText;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Recipe recipe = (Recipe)getItem(position);
View viewToUse;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if(useList){
viewToUse = mInflater.inflate(R.layout.fragment_recipeitem_list, null);
} else {
viewToUse = mInflater.inflate(R.layout.fragment_recipeitem_grid, null);
}
holder = new ViewHolder();
holder.titleText = (TextView)viewToUse.findViewById(R.id.recipe_title);
viewToUse.setTag(holder);
} else {
viewToUse = convertView;
holder = (ViewHolder) viewToUse.getTag();
}
holder.titleText.setText(recipe.getTitle());
return viewToUse;
}
}
my main activity:
public class RecipeBookActivity extends Activity implements DataPassListener {
public static Context CONTEXT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
if(findViewById(R.id.recipe_list_fragment) != null){
if (savedInstanceState != null)
return;
RecipeBookListViewFragment recipeBookListViewFragmentFragment = new RecipeBookListViewFragment();
recipeBookListViewFragmentFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.recipe_list_fragment,
recipeBookListViewFragmentFragment).commit();
}
}
#Override
public void passData(Recipe recipe){
RecipeFragment recipeFragment = new RecipeFragment();
Bundle args = new Bundle();
args.putSerializable(recipeFragment.DATA_RECEIVE, recipe);
recipeFragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.recipe_list_fragment, recipeFragment)
.commit();
}
}
You need to set the onItemClickListener to the ListView before it can register any clicks. Change your onViewCreated code to:
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
recipeList = getListView();
recipeList.setOnItemClickListener(this);
}
That way any item clicks on the ListView will be handled in the onItemClick() method that is overidden in the Fragment.
I am trying to create a custom listview like this: http://i.stack.imgur.com/l8ZOc.png
Currently I managed to create it but there is a problem. For example when there are 8 items, it loads the first 4, then loads the remiaining items as you scroll down. When scrolling down, it works fine.
However, when scrolling back up from bottom, at the middle of list, it instantly moves to top, skipping 2-3-4. items. Then you can scroll down normally again, but when scrolling up, it instantly goes to top of the list.
How can i prevent this from happening?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
<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=".MyActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
Use lazy loading mechanism to load your image data.
There is one nice example here
Hello i would like to start an activity and also a list view from another activity but i can't understand how to do it.
This is the Expandable adapter
public class MyExpandableAdapter extends BaseExpandableListAdapter
{
#SuppressWarnings("unused")
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
// constructor
public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern)
{
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
// method getChildView is called automatically for each child view.
// Implement this method as per your requirement
#SuppressWarnings("unchecked")
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_view, null);
}
// get the textView reference and set the value
textView = (TextView) convertView.findViewById(R.id.textViewChild);
textView.setText(child.get(childPosition));
// set the ClickListener to handle the click event on child item
/* convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
}); */
return convertView;
}
// method getGroupView is called automatically for each parent item
// Implement this method as per your requirement
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = inflater.inflate(R.layout.parent_view, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return 0;
}
#SuppressWarnings("unchecked")
#Override
public int getChildrenCount(int groupPosition)
{
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition)
{
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition)
{
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return false;
}
}
This is my first activity
public class ConversationsListActivity extends ConversationsEssentialActivity{
private String[] drawerListViewItems;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conversations_list);
ActionBar actionBar = getActionBar();
actionBar.show();
FontHelper.applyFont(this, findViewById(R.id.phrasebookList), "fonts/Roboto-Regular.ttf"); /** **/
listView = (ListView) findViewById(R.id.conversationsList);
drawerListViewItems = getResources().getStringArray(R.array.conversations_list_array);
listView.setAdapter(new ArrayAdapter<String>(this,R.layout.conversations_list_items, drawerListViewItems));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
switch (position){
case 0:{
Intent Info = new Intent(ConversationsListActivity.this, ConversationsEssentialActivity.class);
startActivityForResult(Info, position);
setGroupParentsEssential();
setChildDataEssential();
}
break;
}
}
});
}
}
This is my second activity
public class ConversationsEssentialActivity extends Activity{
// Create ArrayList to hold parent Items and Child Items
ArrayList<String> parentItems = new ArrayList<String>();
ArrayList<Object> childItems = new ArrayList<Object>();
ExpandableListView list;
MyExpandableAdapter adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.show();
list = new ExpandableListView(this);
list.setDividerHeight(2);
list.setGroupIndicator(null);
list.setClickable(true);
adapter2 = new MyExpandableAdapter(parentItems, childItems);
adapter2.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
// Set the Adapter to expandableList
list.setAdapter(adapter2);
setContentView(list);
}
// method to add parent Items
public void setGroupParentsEssential()
{
parentItems.add(getResources().getString(R.string.essential_1));
parentItems.add(getResources().getString(R.string.essential_2));
parentItems.add(getResources().getString(R.string.essential_3));
parentItems.add(getResources().getString(R.string.essential_4));
parentItems.add(getResources().getString(R.string.essential_5));
}
// method to set child data of each parent
public void setChildDataEssential()
{
ArrayList<String> child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_1t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_2t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_3t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_4t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_5t));
childItems.add(child);
}
}
the child_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingLeft="0dp"
android:orientation="vertical"
android:id="#+id/childView" >
<TextView
android:id="#+id/textViewChild"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:textSize="20sp"
android:textColor="#75a800"
android:padding="10dp" />
</LinearLayout>
the parent_view.xml
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/textViewGroupName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:textSize="20sp"
android:padding="10dp" />
The first activity, on click, should start the second activity and also launch setGroupParentsEssential(); and setChildDataEssential(); which are declared in the second activity. But on click, it just open the second activity with blank screen.
Does someone provide me an example on how to solve this?
Thank you
If you have created a layout for your activity, try referencing this layout using:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmlfile);
...
}
The layout itself should define the listview