now i have new problem ..... i don't know how initialize dialogfragment in recyclerview and recyclerview in fragment , so who know haw to make it ?
Fragment code:
public View onCreateView( LayoutInflater inflater, ViewGroup container3,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v =inflater.inflate(R.layout.fragment_one_day_tasks,container3,false);
final View vd =inflater.inflate(R.layout.dialogod,null);
TextView textView= (TextView) v.findViewById(R.id.ActiveMenu);
TextView textView1= (TextView) v.findViewById(R.id.Alert);
database = new Database(v.getContext());
mId = database.getLastIdOD();
if(mId>=1) {
oneDayList = database.getOneDayList(1);
}
database.close();
//dlg1 = new DialogFragment();
//GridView gridView = (GridView) v.findViewById(R.id.gridViewActiveOd);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.gridResc);
if(0<mId){
recyclerView.setLayoutManager(new GridAutofitLayoutManager(v.getContext(),350));
recyclerView.setAdapter(new adapterRecylcerViewGridODN(v.getContext(),oneDayList,inflater));
/* gridView.setAdapter(new GridOdAdapter(v.getContext(),oneDayList));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
tapOnAlert(vd,position);
}
});*/
}else{
textView1.setText("You Haven't got any Active Tasks !");
}
FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fabCreateOd);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().finish();
Intent intent = new Intent(getActivity().getApplicationContext(),CreateOneDayNotif.class);
intent.putExtra("mId",1 + database.getLastIdOD());
startActivity(intent);
Snackbar.make(view, "New Task", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
return v;
}
RecyclerView Adapter code:
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.title.setText(mItems.get(position).getTitle());
datecount = new Datecount(mItems.get(position).getDateAndTime());
long minute = datecount.getMinuteInt();
long hour=datecount.getHourInt();
long day=datecount.getDayInt();
long year=datecount.getYearInt();
long month=datecount.getMonthInt();
holder.dataAtime.setText("On date: " + day+"/"+month+"/"+year+ " On time: "+hour+":"+minute);
int iconResId = mContext.getResources().getIdentifier(mItems.get(position).getIcon(), "drawable", mContext.getPackageName());
holder.image.setImageResource(iconResId);
GradientDrawable bgShape = (GradientDrawable) holder.circle.getDrawable();
bgShape.setColor(Color.parseColor(mItems.get(position).getColour()));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I want to put here dialog.show
//I want to put here dialog.show
}
});
And DialogFragment code:
public class DialogFragmentOd extends DialogFragment {
boolean isFabOpen;
Animation fab_open,fab_close,rotate_forward,rotate_backward;
List<OneDayTD> oneDayList;
int position;
Database database;
public static DialogFragmentOd getInstance() {
DialogFragmentOd dialog = new DialogFragmentOd();
//Bundle arguments = new Bundle();
//arguments.putParcelable(Person.class.getName(), person);
//dialog.setArguments(arguments);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View vd = inflater.inflate(R.layout.dialogod, null);
.........
getDialog().setContentView(layout);
return vd;
}
}
So what i need to do ???
Here is an alternative way to handle all clicks in your Activity or Fragment where we have the Context.
Add a custom click listener interface in your Adapter.
public interface OnDataClickListener {
void onDataClick();
}
Create a variable in you Adapter to hold the custom click listener
public MyAdapter {
private OnDataClickListener mOnDataClickListener;
public MyAdapter(OnDataClickListener listener) {
mOnDataClickListener = listener;
}
}
Call the click method of the custom interface when a button is clicked in your ViewHolder
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnDataClickListener.onDataClick();
}
}
Implement View.OnClickListener in your Fragment
MyFragment implement View.OnClickListener {
#Override
public void onClick(View view) {
// Call/Create your dialog fragment show from here.
}
}
Pass the Fragment instance when initialising the Adapter
MyAdapter adapter = new MyAdapter(this);
That's all.
Related
My MainActivity has a recyclerview that will receive the products. In the floatActionButton of MainActivity and I call AddActivity which has the fields to add the product, including a recycler where I insert inputs to compose the price. the problem is exactly in the AddActivity recyclerView
I have a simple recyclerView and the adapter below where I do the CRUD before saving to the database, and everything works except the update, where I update the item through the adapter but the view in the list does not update the data. If you click on the same item to edit it again it shows the values that have already been updated and not those shown in the list.
Below my adapter:
public class InsumoAdapter extends RecyclerView.Adapter<InsumoAdapter.InsumoViewHolder>{
private final Context context;
private List<Insumo> insumos;
public InsumoAdapter(Context context, List<Insumo> insumos) {
this.context = context;
this.insumos = insumos;
}
#Override
public InsumoAdapter.InsumoViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.card_teste, viewGroup, false);
InsumoAdapter.InsumoViewHolder holder = new InsumoAdapter.InsumoViewHolder(view);
return holder;
}
public static class InsumoViewHolder extends RecyclerView.ViewHolder{
public TextView tNome, tVlrCusto;
ImageButton btnDelete;
CardView cardView;
public InsumoViewHolder(View view){
super(view);
tNome = (TextView) view.findViewById(R.id.txtNomeProd);
tVlrCusto = (TextView) view.findViewById(R.id.txtValorProd);
btnDelete = (ImageButton) view.findViewById(R.id.imgBtnDel);
cardView = (CardView) view.findViewById(R.id.cardProduto);
}
}
#Override
public void onBindViewHolder(final InsumoViewHolder holder, final int position) {
if(insumos.size() != 0){
final Insumo p = insumos.get(position);
holder.tNome.setText(p.getNomeInsumo());
holder.tVlrCusto.setText(p.getValor().toString());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicou no Card para Editar na posição "+position,Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
//bundle.putString("nome", p.getNomeInsumo());
//bundle.putDouble("valor", p.getValor());
bundle.putInt("position", position);
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);
//update(p, position);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicou no Card para Excluir na posição "+position,Toast.LENGTH_SHORT).show();
delete(position);
}
});
}
}
#Override
public int getItemCount() {
return this.insumos != null ? this.insumos.size() : 0;
}
private void excluirInsumo(Context context, final int i){
String titulo = "Excluir";
String msg = "Deseja excluir este item?";
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(titulo);
alertDialog.setMessage(msg);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Sim",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//deleta("Pproduto",produtos.get(i).get_id());
AddActivity addActivity = new AddActivity();
//addActivity.deleta(i);
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Não",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void delete(int position){
insumos.remove(position);
notifyItemRemoved(position);
}
public void update(Insumo insumo, int position){
insumos.set(position, insumo);
//notifyItemChanged(position);
notifyDataSetChanged();
}
public void insere(Insumo insumo){
insumos.add(insumo);
notifyDataSetChanged();
}
It's like not going back to onBindViewHolder to update the data. Could someone give me a light? If you need something, but you can't find any way.
Editing-----
AddActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
edtNome = (TextInputEditText) findViewById(R.id.edtNome);
valorCusto = (TextView) findViewById(R.id.txtValorCustoAdd);
valorVenda = (TextView) findViewById(R.id.txtValorVendaAdd);
valorPerc = (TextView) findViewById(R.id.txtValorPercAdd);
addItem = (FloatingActionButton) findViewById(R.id.fltBtnAddItem);
addFoto = (FloatingActionButton) findViewById(R.id.fltBtnAddFoto);
salvar = (FloatingActionButton) findViewById(R.id.fltBtnSalvar);
imgFoto = (ImageView) findViewById(R.id.imgFoto);
recyclerView = (RecyclerView) findViewById(R.id.recy);
edtNome.setTextIsSelectable(true);
valorCusto.setText(valor.toString());
valorPerc.setText("0");
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
InsumoAdapter insumoAdapter = new InsumoAdapter(getApplicationContext(), insumos);
recyclerView.setAdapter(insumoAdapter);
insumoAdapter.notifyDataSetChanged();
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplication(), InsertActivity.class);
startActivity(intent);
}
});
salvar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Produto produto = new Produto();
produto.setpNome(edtNome.getText().toString());
produto.setpValorCusto(somaValor(insumos));
if(foto == 0){
produto.setPfoto(R.drawable.noimage);
}else{
produto.setPfoto(foto);
}
}
});
}
Activity of insumo's insert
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insumo = new Insumo();
insumo.setNomeInsumo(nome.getText().toString());
Log.d(TAG, getClass()+" insumo.getNome = "+insumo.getNomeInsumo());
insumo.setValor(Double.parseDouble(valor.getText().toString()));
Log.d(TAG, getClass()+" insumo.getValor = "+insumo.getValor());
AddActivity addActivity = new AddActivity();
//addActivity.update(insumo, pos);
InsumoAdapter insumoAdapter = new InsumoAdapter(getBaseContext(), addActivity.lista());
insumoAdapter.update(insumo, pos);
insumoAdapter.notifyDataSetChanged();
finish();
}
});
MainAcitvity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerTeste);
FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.fltBtnAdd);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
ProdutoAdapter produtoAdapter = new ProdutoAdapter(getBaseContext(), produtos);
recyclerView.setAdapter(produtoAdapter);
produtoAdapter.notifyDataSetChanged();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
The problem is; you're creating a new instance of adapter instead of using the adapter attached to your recyclerView. Please use the same instance of adapter that's attached to your recyclerView.
In your Activity where your recyclerView is instantiated, use a member reference to contain your reference. i.e. mInsumoAdapter
Then when you create your first adapter instance and attach it to your recyclerView, assign it to mInsumoAdapter.
Finally use the same reference to call your update method.
mInsumoAdapter.update(insumo, pos);
For sharing references between activities and services, you can create a common sharing class like this:
public class ReferenceUtil {
private static InsumoAdapter insumoAdapter;
public static InsumoAdapter getMainAdapter(){
return insumoAdapter;
}
public static void setMainAdapter(InsumoAdapter adapter) {
insumoAdapter = adapter;
}
}
Then use ReferenceUtil.setMainAdapter(adapter); when you click on your FAB, and on your next activity use ReferenceUtil.getMainAdapter(); to obtain your attached reference and update that for your recyclerView to get updated on runtime.
Remember to set the static insumoAdapter in ReferenceUtil to null when you return back to your previous activity because it could lead to a memory leak in your application.
Instead of creating a new Adapter, just use the current adapter instance and use it for update and notifyDataSetChanged.
public InsumoAdapter insumoAdapter;
// Inside onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
....
insumoAdapter = new InsumoAdapter(getApplicationContext(), insumos);
....
}
// Inside Update onClick
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
insumoAdapter.update(insumo, pos)
insumoAdapter.notifyDataSetChanged()
}
Try with using notifyDataSetChnaged() in the activity from where you are passing the list to the adapter or you could do it after updating it. something like this,
RecyclerView.setAdapter(this,list);
notifyDataSetChanged();
or
InsumoAdapter.update(list,pos);
notifyDataSetChanged();
You could try use this way for all the CRUD operations.
I have a BottomSheetDialogFragment class like this
RenameWalletDialog
public class RenameWalletDialog extends com.google.android.material.bottomsheet.BottomSheetDialogFragment {
EditText editTextWalletName;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rename_wallet_sheet, container, false);
editTextWalletName = (EditText) view.findViewById(R.id.custom_input_et);
view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Confirm button clicked", Toast.LENGTH_SHORT).show();
}
});
view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
view.findViewById(R.id.clear_field).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTextWalletName.getText().clear();
}
});
return view;
}
}
and I created a function it in my adapter class like this
WalletAdapter
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.wallet_item, parent, false);
final DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
dataObjectHolder.walletoptions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(v.getContext(), "Option Click " + dataObjectHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
// Log.d(TAG, "position = " + dataObjectHolder.getAdapterPosition());
Context wrapper = new ContextThemeWrapper(mCtx, R.style.popupMenuStyle);
final PopupMenu popup = new PopupMenu(wrapper, v, Gravity.END);
popup.inflate(R.menu.poupup_menu);
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
showFragmentRenameWallet();
break;
case R.id.two:
//Do operation if menu_item_two
Toast.makeText(mCtx,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
}
});
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, final int position) {
DecimalFormat formatter = new DecimalFormat("#,###,###");
Double doubleBalance = (double) userWalletList.get(position).getBalance();
String numberFormatBalance = formatter.format(doubleBalance);
holder.walletname.setText(userWalletList.get(position).getWalletName());
holder.walletbalance.setText(String.valueOf( "₦ " +numberFormatBalance));
// holder.walletid.setText(String.valueOf(userWalletList.get(position).getWalletid()));
RenameWalletDialog renameWalletFragment = new RenameWalletDialog();
renameWalletFragment.show(((FragmentActivity)mCtx).getSupportFragmentManager(), renameWalletFragment.getTag());
Bundle bundle = new Bundle();
String walletN = userWalletList.get(position).getWalletName();
bundle.putString("walletname", walletN);
renameWalletFragment.setArguments(bundle);
}
#Override
public int getItemCount() {
return userWalletList.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private void showFragmentRenameWallet(){
RenameWalletDialog renameWalletFragment = new RenameWalletDialog();
renameWalletFragment.show(((FragmentActivity)mCtx).getSupportFragmentManager(), renameWalletFragment.getTag());
}
and use the function like this
showFragmentRenameWallet();
I think everyone now has a basic idea how my code logic works
I am trying to achieve;
I want to set the edit text view of the bottom sheet to the name of wallet the user clicks the rename option for
But I don't see any feasible way of doing this via the adapter, since it's not really a part of the adapter view
Does any one have any idea on how to do this?
NB: In the on bind view holder for my adapter, I get the wallet name like this
holder.walletname.setText(userWalletList.get(position).getWalletName());
Do this if you want to pass data via bundle then
In Adapter:
Bundle bundle = new Bundle()
bundle.putString(SomeKey, value you want to send)
walletFragmentObject.setArguments(bundle)
Then in fragment
String text = getArguments.getString(SomeKey)
Update:
Change your method as shown below:
private void showFragmentRenameWallet(ViewHolder dataObjectHolder) {
RenameWalletDialog renameWalletFragment = new RenameWalletDialog();
Bundle bundle = new Bundle();
String walletN = userWalletList
.get(dataObjectHolder.getAdapterPosition())
.getWalletName();
bundle.putString("walletname", walletN);
renameWalletFragment.show(
((FragmentActivity) mCtx).getSupportFragmentManager(),
renameWalletFragment.getTag()
);
}
Remove code related to bundle and RenameWalletDialog from onBindViewHolder.
I have a MainActivity hosted a fragment called FragmentOne
and there is another Activity named DetailPagerActivity hosted another fragment called DetailFragment
i want to use a method from DetailFragment in FragmentOne
.. how can i do this?
i tried to use FragmentManager and so on, but failed
i want to call getDetailReport() from DeatilFragment in onSwiped > FragmentOne
here is my FragmentOne :
public class FragmentOne extends Fragment {
private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); }
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one_layout,
container, false);
mDetailRecyclerView = (RecyclerView)
view.findViewById(R.id.detail_recycler_view);
..
..
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}
private class DetailHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private TextView mTitleTextView;
private Detail mDetail;
private RatingBar mRatingBar;
public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_detail,
parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
}
public void bind(Detail detail) {
mDetail = detail;
mTitleTextView.setText(mDetail.getTitle());
mRatingBar.setRating(mDetail.getRate()); }
#Override
public void onClick(View view) {
Intent intent = DetailPagerActivity.newIntent(getActivity(),
mDetail.getId());
startActivity(intent); }
return true;
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
private List<Detail> mDetails;
public DetailAdapter(List<Detail> details) {
mDetails = details;
}
#Override
public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(getActivity());
return new DetailHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(DetailHolder holder, int position) {
Detail detail = mDetails.get(position);
holder.bind(detail);
}
#Override
public int getItemCount() {
return mDetails.size();
}
public void setDetails(List<Detail> details) {
mDetails = details;
////////////////////////////////////////////////////////////////////////////////////////////////////////
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
private Detail mDetail;
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
final int position = viewHolder.getAdapterPosition(); //get position which is swipe
if (direction == ItemTouchHelper.LEFT) { //if swipe left
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //alert for confirm to delete
builder.setMessage("Are you sure to delete?"); //set message
builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() { //when click on DELETE
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, getDetailReport());
i.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.detail_report_subject));
i = Intent.createChooser(i, getString(R.string.send_report));
startActivity(i);
//////////////////////////////////////////////////////
// mAdapter.notifyItemRemoved(position); //item removed from recylcerview
// DetailLab.get(getActivity()).deleteDetail(mDetail);
// updateUI();
// updateNumbers();
dialog.dismiss();
// return;
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { //not removing items if cancel is done
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show(); //show alert dialog
}
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(mDetailRecyclerView); //set swipe to recylcerview
}
}
}
and this is my DetailFargment:
public class DetailFragment extends Fragment {
private static final String ARG_DETAIL_ID = "detail_id";
private static final String DIALOG_DATE = "DialogDate";
private static final String DIALOG_PHOTO = "DialogPhoto";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_PHOTO = 2;
..
..
public static DetailFragment newInstance (UUID detailId) {
Bundle args = new Bundle();
args.putSerializable(ARG_DETAIL_ID, detailId);
DetailFragment fragment = new DetailFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
UUID detailId = (UUID) getArguments().getSerializable(ARG_DETAIL_ID);
mDetail = DetailLab.get(getActivity()).getDetail(detailId);
mPhotoFile = DetailLab.get(getActivity()).getPhotoFile(mDetail);
}
#Override
public void onPause() {
super.onPause();
DetailLab.get(getActivity()).updateDetail(mDetail);
}
#Override
public View onCreateView (LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_detail,
container, false);
..
..
/////////////////////////// Report Button
mReportButton = (Button) v.findViewById(R.id.detail_report);
mReportButton.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, getDetailReport());
i.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.detail_report_subject));
i = Intent.createChooser(i, getString(R.string.send_report));
startActivity(i);
}
});
..
..
return v;
}
#Override
public void onResume() {
super.onResume();
}
//////////////////////////////////// REPORT
private String getDetailReport() {
String dateFormat = "EEE, MMM dd";
String dateString = DateFormat.format(
dateFormat, mDetail.getDate()).toString();
String rateString = null;
String report = getString(R.string.detail_report,
mDetail.getTitle(), dateString,
rateString, rateString
);
return report;
}
..
..}
You should move the getDetailsReport() out of the fragment and into some sort of data/utility class - then you can call it from both places. Data should be separate from the UI especially if you need to use it in more than one Activity/Fragment.
If you want to communicate between unrelated activities/fragments, the easiest way is to use a Broadcast / BroadcastReceiver. This is usually used to notify the other activity/fragment that something needs to be updated - as opposed to trying to query the other activity/fragment for data. Usually the fragment/activity will update if it receives a broadcast or be in a good state if it is initialized from scratch.
The issue you will run into when making activities/fragment rely on other activities/fragment is that the one not being shown can be cleaned up - so you can't rely on the action actually happening.
How to popup a new fragment and reuse it (depending on the item selected ) When an item from the ListView is clicked. I already tried to use OnItemClickListener() instead of OnClickListene
public void onItemClick(AdapterView parent, View view, int position, long id)
but it is not working either, any help would be appreciated
please refer to the screenshot attached
Thanks
-- Fragment ListView Class--
public class WorkOutFragmentForearm extends Fragment {
private String[] exercisesForearmNames; private String[] exerciseForearmType;
private String[] exerciseForeamNumber;
private int[] image = { R.drawable.forearm,
};
private ArrayList<WorkOutListNameListExercises> mForearmsArray;
private RecyclerView mForearmRecyclerView; private ForearmAdapter mAdapter;
#Override public void onCreate(Bundle savedInstanceState) {
Resources res = getResources();
// Initialize array from info form XML strings exercisesForearmNames =
res.getStringArray(R.array.exercisesForearmNames); exerciseForearmType =
res.getStringArray(R.array.exerciseForearmType); exerciseForeamNumber =
res.getStringArray(R.array.exerciseForeamNumber);
mForearmsArray = new ArrayList<>();
for (int i = 0; i < exercisesForearmNames.length; i++) {
WorkOutListNameListExercises s = new WorkOutListNameListExercises();
s.setName(exercisesForearmNames[i]);
s.setExerciseType(exerciseForearmType[i]);
s.setExerciseNumber(exerciseForeamNumber[i]); s.setImageId(image[i]);
mForearmsArray.add(s); }
super.onCreate(savedInstanceState);
}// end Main
#Override public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.workout_recycler_forearm, container,
false); mForearmRecyclerView = (RecyclerView)
view.findViewById(R.id.recycler_view);
mForearmRecyclerView.addItemDecoration(new
SimpleDividerItemDecoration(getResources()));
mForearmRecyclerView.setLayoutManager(new
LinearLayoutManager(getActivity())); updateUI();
// -------------------------------------------------------------------------
---------- // When Back Button is clicked
view.setFocusableInTouchMode(true); view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() { #Override public boolean
onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Display Drawer when back button is clicked if drawer not // display
not go back without FragmentTransaction Code
MainActivity.mDrawerLayout.openDrawer(Gravity.LEFT);
return true; } else {
return false; } } });
return view;
}// end Main
private void updateUI() { mAdapter = new ForearmAdapter(mForearmsArray);
mForearmRecyclerView.setAdapter(mAdapter); }
// Inner Class private class ForearmHolder extends RecyclerView.ViewHolder {
private WorkOutListNameListExercises mForearm; public ImageView mImageView;
public TextView mNameTextView; public TextView mTypeNumberTextView;
public ForearmHolder( View itemView){ super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView);
mNameTextView = (TextView)
itemView.findViewById(R.id.textview_name); mTypeNumberTextView =
(TextView) itemView.findViewById(R.id.textview_type_number);
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Bundle bundle = new Bundle();
if (mForearm.getName().equals(exercisesForearmNames[0])) {
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction(); Fragment
fragmentItem1 = new FragmentItem1(); fragmentItem1.setArguments(bundle);
fragmentTransaction.add(R.id.my_frame_list, fragmentItem1);
fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
Toast.makeText(getActivity(),mForearm.getName() + "Item 1",
Toast.LENGTH_SHORT).show(); }
});//end View.OnClickListener
}// end Method
public void bindData(WorkOutListNameListExercises s) { mForearm = s;
mImageView.setImageResource(s.getImageId());
mNameTextView.setText(s.getName());
mTypeNumberTextView.setText(s.getExerciseType() + ":" +
s.getExerciseNumber());
}
}// end Inner Class
// Inner Class private class ForearmAdapter extends
RecyclerView.Adapter<ForearmHolder>
{ private ArrayList<WorkOutListNameListExercises> mForearmsArray;
public ForearmAdapter(ArrayList<WorkOutListNameListExercises>
WorkOutListNameListExercises) { mForearmsArray =
WorkOutListNameListExercises;
}
#Override public ForearmHolder onCreateViewHolder(ViewGroup parent, int
viewType) { LayoutInflater layoutInflater =
LayoutInflater.from(getActivity()); View view =
layoutInflater.inflate(R.layout.workout_items_list_info, parent, false);
return new ForearmHolder(view);
}
#Override public void onBindViewHolder(ForearmHolder holder, int position) {
WorkOutListNameListExercises s = mForearmsArray.get(position);
holder.bindData(s);
}
#Override public int getItemCount() { return mForearmsArray.size();
} }// end Inner Class
}// end Class
WorkOutListNameListExercises.java
public class WorkOutListNameListExercises { private String ExreciseName; private
String ExerciseType; private String ExerciseNumber; private int ExerciseImageId;
public String getName() { return ExreciseName; }
public void setName(String ExreciseName) { this.ExreciseName = ExreciseName; }
public String getExerciseType() { return ExerciseType; }
public void setExerciseType(String ExerciseType) { this.ExerciseType =
ExerciseType; }
public String getExerciseNumber() { return ExerciseNumber; }
public void setExerciseNumber(String ExerciseNumber) { this.ExerciseNumber =
ExerciseNumber; }
public int getImageId() { return ExerciseImageId; }
public void setImageId(int ExerciseImageId) { this.ExerciseImageId =
ExerciseImageId; } }
Okay! So you are using a recyclerview and on the itemview you have also added an onClickListener. Also you are creating bundle there. Well you are 99% already there!
You haven't added anything into the bundle. To add some values into it do
bundle.putString("key1","value1");
You can pass an Array as well as an ArrayList using putStringArray() and putStringArrayList()
We don't need to check whether its the first, second or the third item the user is clicking on. Do this in the bindData() which is already providing us the position of the item, using this position we will pass the appropriate values to the fragment. So our code will look like this.
public void bindData(WorkOutListNameListExercises s) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("forearmName",s.getName());
bundle.putString("forearmType",s.getType());
bundle.putString("forearmNumber",s.getNumber());
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragmentItem1 = new FragmentItem1();
fragmentItem1.setArguments(bundle);
fragmentTransaction.add(R.id.my_frame_list, fragmentItem1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
//Your Toast message!
}
}
}
Now on the FragmentItem1 to reuse it. Do this in the onCreate
private String exercisesForearmName, exerciseForearmType, exerciseForeamNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
Bundle bundle=this.getArguments();
exercisesForearmNames=bundle.getString("forearmName");
exerciseForearmType=bundle.getString("forearmType");
exerciseForearmNumber=bundle.getString("forearmNumber");
}
now just assign the values to the view which you intend to in the onCreateView()
Done. Hope this helps.
I created a custom dialogfragment it consists of a recyclerview and a button, when I click on a item it is selected,it should highlighted and when clicking on button I want the particular item position or data of particular item get to my main activity. I tried with different code but not getting it, referred different answers and tried. please help me.
Thanks in advance.
DialogFragment:
public class DiaFragment extends DialogFragment {
RecyclerView recyclerView;
public DiaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
recyclerView = (RecyclerView) v.findViewById(R.id.list);
ListAdapter listAdapter = new ListAdapter(getContext(),getData());
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return v;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return super.onCreateDialog(savedInstanceState);
}
public static List<Listen> getData()
{
List<Listen> data = new ArrayList<>();
int[] images = {R.drawable.bottle,R.drawable.lotion,R.drawable.soap,R.drawable.soda,R.drawable.sodaa};
String[] texts = {"250ml","300ml","500ml","750ml","1ltr"};
for (int i=0;i<texts.length && i<images.length;i++){
Listen current = new Listen();
current.img = images[i];
current.text= texts[i];
data.add(current);
}
return data;
}
}
recycleview adapter:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MyViewHolder> {
private LayoutInflater inflater;
List<Listen> data = Collections.emptyList();
private int selectedPos = 0;
public ListAdapter(Context context,List<Listen> data){
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Listen current = data.get(position);
holder.text1.setText(current.text);
holder.imge.setImageResource(current.img);
holder.itemView.setSelected(selectedPos == position);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView text1;
public ImageView imge;
public MyViewHolder(View itemView) {
super(itemView);
text1 = (TextView) itemView.findViewById(R.id.texty);
imge = (ImageView) itemView.findViewById(R.id.ivy);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notifyItemChanged(selectedPos);
selectedPos = getAdapterPosition();
notifyItemChanged(selectedPos);
}
});
}
}
#Override
public int getItemCount() {
return data.size();
}
}
From your Dialog, you can call getActivity() to access to the activity who launch the Dialog. Then by cast getActivity() with your activity class name, you can access to a protected method and set data.
class MyActivity extends Activity {
private Listen selectedListen;
...
protected void setDataFromMyDialog(Listen listen) {
this.selectedListen = listen;
}
...
}
public class DiaFragment extends DialogFragment {
...
protected ListAdapter listAdapter;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
listAdapter = new ListAdapter(getContext(),getData());
...
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).setDataFromMyDialog(listAdapter.getSelectedData());
dismiss(); // close dialog
}
});
return super.onCreateDialog(savedInstanceState);
}
}
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MyViewHolder> {
...
public Listen getSelectedData() {
return data.get(selectedPos);
}
...
}