A silly question but I am new to Android and I’ve spent a few hours looking around but can’t find the answer.
I have a dialog fragment with a recyclerview in it. I want the dialog to close when the user clicks a recyclerview item. How do I call dismiss() from the listener in recyclerview adapter?
I've tried a listener for the recyclerview in the dialog fragment but it does nothing. please help.
This is the dialog fragment. At the bottom onClick dismisses it:
public class EvMySchedDlg extends DialogFragment implements View.OnClickListener {
View view;
String eventId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.event_my_sched, container, false);
ImageView closeButton = view.findViewById(R.id.closeButton3);
closeButton.setOnClickListener(this);
final TextView eventNameBox = view.findViewById(R.id.eventNameBox);
eventNameBox.setOnClickListener(this);
TextView coNameBox = view.findViewById(R.id.coNameBox);
Bundle extraData = getArguments();
eventId = extraData.getString("eventId");
String coName = extraData.getString("coName");
String eventName = extraData.getString("eventName");
coNameBox.setText(coName);
eventNameBox.setText(eventName);
//get list of days from server
String userId = ((DrawerActivity)getContext()).getUserData("userId");
final String[] cred = new String[]{"user_id", userId, "event_id", eventId};
VolleyCalls.postRequest(this.getContext(), "getEventDays", cred, new VolleyCalls.ServerReply() {
#Override
public void onSuccess(String theReply){
final List<EvMySchedData> dayList = new ArrayList<>();
EvMySchedAdapter tAdapter = new EvMySchedAdapter(dayList);
RecyclerView recyclerView = view.findViewById(R.id.schedRecycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(tAdapter);
tAdapter.emptyRecycler();
try {
JSONObject jsonServerReply = new JSONObject(theReply);
int evCount = jsonServerReply.getInt("recCount");
EvMySchedData thisLine;
if (evCount > 0) {
JSONObject cRec =null;
for (int thisRec=0; thisRec<evCount; thisRec++ ) {
cRec = jsonServerReply.getJSONObject(String.valueOf(thisRec));
thisLine = new EvMySchedData(cRec.getString("day_date"), cRec.getString("day_times"), cRec.getString("role"), cRec.getString("room"), view.getContext());
dayList.add(thisLine);
}
}
} catch (Exception e) {
}
}
public void onError(String error) {
}
});
return view;
} // end onCreateView
public void onClick(View v) {
this.dismiss();
}
}
The recyclerview has the picture of an eye on each line. I want to load a new fragment and close the dialog fragment when the eye is clickd. This is the adapter code:
public class EvMySchedAdapter extends RecyclerView.Adapter<EvMySchedAdapter.EventViewHolder> {
private List<EvMySchedData> dayList;
public EvMySchedAdapter(List<EvMySchedData> dayList) {
this.dayList = dayList;
}
#Override
public EvMySchedAdapter.EventViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_my_sched_row, parent, false);
ImageView eye = itemView.findViewById(R.id.dayOverviewButton);
try {
eye.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Load a new fragment
//dismiss the dialog
}
});
} catch (Exception e) {
}
return new EvMySchedAdapter.EventViewHolder(itemView);
}
#Override
public void onBindViewHolder(EvMySchedAdapter.EventViewHolder holder, int position) {
holder.dayDateBox.setText(dayList.get(position).getDayDate());
holder.dayTimeBox.setText(dayList.get(position).getDayTime());
holder.dayRoleBox.setText(dayList.get(position).getDayRole());
holder.dayRoomBox.setText(dayList.get(position).getDayRoom());
} // end onBindViewHolder
#Override
public int getItemCount() {
return dayList.size();
}
public class EventViewHolder extends RecyclerView.ViewHolder {
public TextView dayDateBox;
public TextView dayTimeBox;
public TextView dayRoleBox;
public TextView dayRoomBox;
public Context context;
public EventViewHolder(View view) {
super(view);
dayDateBox = view.findViewById(R.id.dateBox);
dayTimeBox = view.findViewById(R.id.timeBox);
dayRoleBox = view.findViewById(R.id.roleBox);
dayRoomBox = view.findViewById(R.id.roomBox);
}
}
public void emptyRecycler() {
final int size = dayList.size();
dayList.clear();
notifyItemRangeRemoved(0, size);
}
}
Thanks
Add to the adapter a constructor that receive DialogFragment and save it as a field.
When you create the Adapter do new EvMySchedAdapter(dayList, EvMySchedDlg.this);
Inside the onClick call dialgFragment.dismiss();
for Kotlin Users
class SomeAdapter(private val dialog: BottomSheetDialog):RecyclerView.Adapter<SomeAdapter.ViewHolder>()
holder.itemView.setOnClickListener{
dialog.dismiss()
}
Related
In MainActivity I have NavigationDrawer. For each menu item, I have a fragment class with a corresponding layout. One of them is MyCardFragment.java. In this fragment, I am showing CardView through RecyclerView.
My CardView contains some TextViews and an ImageView. What I wanted is when a user clicks a widget it will open a custom input dialog (contains a TextView, an EditText, a positive button, and a negative button) for updating data in Firebase Real-time database. I created a dialog fragment class, but don't know how to implement it in my adapter class.
This is my main activity which holds RecyclerView and CardView:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser != null){
myRef = FirebaseDatabase.getInstance().getReference().child("user").child(currentUser.getUid());
}
mContext = MainActivity.this;
mDrawerLayout = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_action_name);
NavigationView navigationView = findViewById(R.id.nav_view);
//navigationView.inflateHeaderView(R.layout.nav_header);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
switch (menuItem.getItemId()) {
case R.id.nav_myCards:
menuItem.setChecked(true);
getSupportActionBar().setTitle("MY Cards");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,new MyCardFragment())
.commit();
break;
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
navigationView.getMenu().getItem(0).setChecked(true);
//Highlighted
//onNavigationItemSelected(navigationView.getMenu().getItem(0));
setupFirebaseAuth();
if (currentUser != null){
//updateNavHeader();
}
}
Custom Dialog Fragment:
DialogCompanyAddress.java:
public class DialogCompanyAddress extends DialogFragment {
public DialogCompanyAddress() {
// Required empty public constructor
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.fragment_dialog_company_address,null));
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//save data to the firebase
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do
}
});
return builder.create();
}
}
finally the adapter:
RecyclerviewAdapter.java:
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
Context mContext;
List<Template> listdata;
public RecyclerviewAdapter(Context context,List<Template> listdata) {
this.mContext = context;
this.listdata = listdata;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/*// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;*/
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview,parent,false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0) {
arr = 0;
} else {
arr=listdata.size();
}
} catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname,tempID;
ImageView logo_image;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(final View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext,"Clicked on Address",Toast.LENGTH_SHORT).show();
DialogCompanyAddress address = new DialogCompanyAddress();
//address.show(getSupportFragmentManager);--->This line give me error
}
});
}
}
use a interface in your adapter like below
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
public interface ClickListner {
void IconClick(Template template);
}
Context mContext;
List<Template> listdata;
private final ClickListner listner;
public RecyclerviewAdapter(Context context, List<Template> listdata, ClickListner listner) {
this.mContext = context;
this.listdata = listdata;
this.listner = listner;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
holder.bind(listdata.get(position), listner);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try {
if (listdata.size() == 0) {
arr = 0;
} else {
arr = listdata.size();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder {
TextView pname, caddress, pemail, pdesignation, pphone, cname, tempID;
ImageView logo_image;
public MyHolder(final View itemView) {
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
// caddress.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// //Toast.makeText(mContext,"Clicked on
Address",Toast.LENGTH_SHORT).show();
// DialogCompanyAddress address = new DialogCompanyAddress();
// //address.show(getSupportFragmentManager);--->This line give me
error
//
// }
// });
}
public void bind(final Template template, final ClickListner Listner) {
// DeleteIcon.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// delListner.onDeleteIconClick(card, position);
// }
// });
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listner.IconClick(template);
}
});
}
}
and in your fragment you need to initialize the adapter. when initialize you can override the ClickListner interface.
I'm having a problem with making a RecycleView in a fragment with data from Firebase. I expect the app to show the RecycleView after I clicked on a button to change from one fragment to the RecycleView fragment, but it does change the showed fragment but it does not show anything.
I know there are plenty of questions like this but I don't seem to find the correct solution to this problem.
I've made everything needed for a Firebase RecyclerView, and also tried to build it inside an activity instead fragment and it did work, but not with the fragment.
I've tried to initialize the adapter and recyclerview inside the onCreateView method, onActivityCreated, and onViewCreated method and none of them seem to be working.
Here's my fragment code:
private KidAdapter adapter;
private RecyclerView recyclerView;
Button button;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.uangsaku_menu_fragment, container, false);
button = view.findViewById(R.id.btn_add);
button.setOnClickListener(this);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
setUpRecyclerView();
return view;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_add){
Intent intent = new Intent(getActivity(), Register.class);
startActivity(intent);
}
}
public void setUpRecyclerView(){
Query query = FirebaseDatabase.getInstance().getReference("kids");
FirebaseRecyclerOptions<kidData> options = new FirebaseRecyclerOptions.Builder<kidData>()
.setQuery(query, kidData.class)
.build();
adapter = new KidAdapter(options);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
if (adapter != null) {
adapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
The adapter class
public class KidAdapter extends FirebaseRecyclerAdapter<kidData, KidAdapter.KidViewHolder> {
public KidAdapter(#NonNull FirebaseRecyclerOptions<kidData> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull KidViewHolder holder, int position, #NonNull kidData model) {
holder.nama.setText(model.getKidName());
holder.balance.setText(model.getKidBalance());
holder.limit.setText("Limit: "+model.getKidLimit());
holder.spending.setText("Spending xxx.xxx");
}
#NonNull
#Override
public KidViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.kids_card,
viewGroup, false);
return new KidViewHolder(v);
}
public class KidViewHolder extends RecyclerView.ViewHolder {
TextView nama, balance, limit, spending;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.tv_nama);
balance = itemView.findViewById(R.id.tv_balance);
limit = itemView.findViewById(R.id.tv_dailylimit);
spending = itemView.findViewById(R.id.tv_dailyspending);
}
}
}
The kidData model class
public class kidData {
String kidName, kidEmail, kidDoB, kidLimit, kidBalance;
public kidData(){
}
public kidData(String kidName, String kidEmail, String kidDoB, String kidLimit, String kidBalance) {
this.kidName = kidName;
this.kidEmail = kidEmail;
this.kidDoB = kidDoB;
this.kidLimit = kidLimit;
this.kidBalance = kidBalance;
}
public String getKidName() {
return kidName;
}
public String getKidEmail() {
return kidEmail;
}
public String getKidDoB() {
return kidDoB;
}
public String getKidLimit() {
return kidLimit;
}
public String getKidBalance() {
return kidBalance;
}
}
The problem in your code is the use of the following line of code:
recyclerView.setHasFixedSize(true);
And this is because when using the latest version of Firebase-UI library, there is no need to set the size of the RecyclerView as fixed. The solution for solving this problem is to simply remove/comment the above line of code. That's it!
I have a RecyclerView.Adapter which has some Arrays there.
ArrayList with Strings and ArrayList with Integer. Strings are like url and Integer is the photo.
When the app is open for first time the first item is selected.
I have another method for click which makes another item as selected and this works, but the problem is that the first item stays as selected and so for every image click makes as selected, I want only one item to be selected and take a color.
This is my code.
Adapter of RecyclerView
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
And this is the MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
Initialize your selected item globally
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem = 0;
.....
Then inside your onBindViewHolder whenever you click a new Image notify your adapter for changes in the last selected item cell.
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousSelectedItem = selectedItem;
selectedItem = i;
notifyItemChanged(previousSelectedItem);
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
});
Just remove this line from onBindViewHolder
selectedItem = 0;
and add an else to the background condition, like:
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}else{
viewHolder.image.setBackgroundColor(“YOUR_DEFAULT_COLOR”);
}
and update the onClick:
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = i;
notifyDataSetChanged();
}
});
I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
This is a multi-part question.
First Part:
I'm building an app to track local events. Currently, I have a Fragment containing a RecyclerView consisting of CardViews which each represent one event. What I want is to be able to tap a card and replace the Fragment with a new one showing more details about that card's event.
I've searched Google for several hours, but it none of the solutions presented seemed to work when I tried them. Below is the class for the fragment Tab1 which creates the RecyclerView adapter.
public class Tab1 extends Fragment {
//RecyclerView
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
//ProgressDialog
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "removed";
// JSON Node names
private static final String TAG_EVENT = "event";
private static final String TAG_EVENTNAME = "Event Name";
private static final String TAG_LOCATION = "Location";
private static final String TAG_RAINLOCATION = "Rain Location";
private static final String TAG_ORG = "Org";
private static final String TAG_TIME = "Time";
private static final String TAG_RSVP = "RSVP";
// events JSONArray
JSONArray events = null;
private List<Event> eventlist;
private RecyclerView rv;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_2,container,false);
// Calling async task to get json
new GetEvents().execute();
return v;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
mRecyclerView = (RecyclerView) getView().findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
}
private class GetEvents extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
eventlist = new ArrayList<>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
events = jsonObj.getJSONArray(TAG_EVENT);
// looping through All Events
for (int i = 0; i < events.length(); i++) {
JSONObject c = events.getJSONObject(i);
String eventName = c.getString(TAG_EVENTNAME);
String location = c.getString(TAG_LOCATION);
String rain = c.getString(TAG_RAINLOCATION);
String org = c.getString(TAG_ORG);
String time = c.getString(TAG_TIME);
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, h:mm a", Locale.US);
SimpleDateFormat parserSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
try {
Date date = parserSDF.parse(time);
time = format.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
String rsvp = c.getString(TAG_RSVP);
eventlist.add(new Event(eventName, time.toUpperCase(), location, R.drawable.pace));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
RVAdapter adapter = new RVAdapter(eventlist);
mRecyclerView.setAdapter(adapter);
}
}
}
And here is the RVAdapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.EventViewHolder> {
public static class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView eventName;
TextView eventTime;
TextView eventLocation;
ImageView orgPhoto;
private ClickListener clickListener;
EventViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
eventName = (TextView)itemView.findViewById(R.id.event_name);
eventTime = (TextView)itemView.findViewById(R.id.event_time);
eventLocation = (TextView)itemView.findViewById(R.id.event_location);
orgPhoto = (ImageView)itemView.findViewById(R.id.org_photo);
itemView.setOnClickListener(this);
}
public interface ClickListener {
/**
* Called when the view is clicked.
*
* #param v view that is clicked
* #param position of the clicked item
*/
public void onClick(View v, int position, String title);
}
/* Setter for listener. */
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public void onClick(View v) {
clickListener.onClick(v, getPosition(), eventName.getText().toString());
}
}
List<Event> events;
RVAdapter(List<Event> events){
this.events = events;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_card, viewGroup, false);
EventViewHolder pvh = new EventViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(EventViewHolder EventViewHolder, final int i) {
EventViewHolder.eventName.setText(events.get(i).name);
EventViewHolder.eventTime.setText(events.get(i).time);
EventViewHolder.eventLocation.setText(events.get(i).location);
EventViewHolder.orgPhoto.setImageResource(events.get(i).orgPhoto);
EventViewHolder.setClickListener(new EventViewHolder.ClickListener() {
#Override
public void onClick(View v, int pos, String title) {
//onClick
}
});
}
#Override
public int getItemCount() {
return events.size();
}
}
You can see I've attempted to implement the interface and onClickListener.
Is this the right way? I've tried to test it by making toasts with the name of the Card clicked, but it doesn't appear to have worked, or at least the toast is not showing up.
Second Part:
If this is the correct way and it should be working, where/how do I write the code to replace the fragment with the new one showing more information about the event? Can it go in the Adapter class? The Tab1 fragment is actually inside of another fragment which is inside of an activity. I'd like to replace Tab1's parent fragment.
See if this helps
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.EventViewHolder> {
public static class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView eventName;
TextView eventTime;
TextView eventLocation;
ImageView orgPhoto;
EventViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
eventName = (TextView) itemView.findViewById(R.id.event_name);
eventTime = (TextView) itemView.findViewById(R.id.event_time);
eventLocation = (TextView) itemView.findViewById(R.id.event_location);
orgPhoto = (ImageView) itemView.findViewById(R.id.org_photo);
}
#Override
public void onClick(View view) {
//do stuff
}
}
List<Event> events;
RVAdapter(List<Event> events){
this.events = events;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_card, viewGroup, false);
return new EventViewHolder(v);
}
#Override
public void onBindViewHolder(EventViewHolder EventViewHolder, final int i) {
EventViewHolder.eventName.setText(events.get(i).name);
EventViewHolder.eventTime.setText(events.get(i).time);
EventViewHolder.eventLocation.setText(events.get(i).location);
EventViewHolder.orgPhoto.setImageResource(events.get(i).orgPhoto);
}
#Override
public int getItemCount() {
return events.size();
}
}
For the 2nd part of your question. Its better for the ParentActivity hosting both Frag1 & Frag2 to switch the fragment. So say in the ParentActivity, there is a framelayout (R.id.container) that is hosting Frag1.
You can pass the event call back to the activity, and you can do this to replace the fragment in the container
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, Frag2)
.commit();