DialogFragment show only the Buttons even the layout has more - android

As the picture show the DialogFragment It´s all white except for the Buttons. I have tried all kinds of layout parrams and ConstraintLayout settings but the white background feels like it´s some z-order thing,
Please advice
This is what the ANdroid Studio layout editor look likes
My xml:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:srcCompat="http://schemas.android.com/tools"
android:id="#+id/place_search_dialog"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:visibility="visible">
<ImageView
android:id="#+id/place_search_dialog_header_image_IV"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:contentDescription=""
android:scaleType="centerCrop"
app:layout_constraintBottom_toTopOf="#+id/guideline478"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
srcCompat:src="#drawable/place_picker_dialog_nobackground"/>
<Button
android:id="#+id/btn_place_dialog_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:padding="10dp"
android:text="#string/cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/btn_place_dialog_ok"/>
<Button
android:id="#+id/btn_place_dialog_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:padding="10dp"
android:text="#string/ok"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btn_place_dialog_cancel"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintStart_toStartOf="parent"/>
<android.support.constraint.Guideline
android:id="#+id/guideline355"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.66"/>
<ImageView
android:id="#+id/imageView_street"
android:layout_width="74dp"
android:layout_height="48dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/btn_place_dialog_cancel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.348"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/place_search_dialog_header_image_IV"
app:layout_constraintVertical_bias="0.581"
app:srcCompat="#drawable/avatar"/>
<android.support.constraint.Guideline
android:id="#+id/guideline478"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.28"/>
</android.support.constraint.ConstraintLayout>
UPDATE
This is the DialogFragment
public class GooglePlaceDetailsDialogFragment extends DialogFragment {
private View mRootView;
private BasePlace place;
private Unbinder unbinder;
RequestResponse requestResponse;
private PlaceDetails placeDetails;
public interface ShowPlaceListener {
void onShowPlace(BasePlace item);
}
private ShowPlaceListener mShowPlaceListener;
public static GooglePlaceDetailsDialogFragment newInstance(BasePlace item) {
GooglePlaceDetailsDialogFragment fragment = new GooglePlaceDetailsDialogFragment();
fragment.setPlace(item);
return fragment;
}
// Called to do initial creation of a fragment. This is called after onAttach and before onCreateView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mShowPlaceListener = (ShowPlaceListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement Callback ShowPlaceListener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.dialog_fragment_show_google_place_details, container);
ImageView imageViewStreet = mRootView.findViewById(R.id.imageView_street);
// Just unpack the details to make it smoother
this.requestResponse = place.requestResponse;
this.placeDetails = place.requestResponse.placeDetails;
unbinder = ButterKnife.bind(this, mRootView);
getDialog().setTitle("lkjkjlkj ");
if (placeDetails.url.equals("")) {
if (LogManager.isDebugable()) {
Picasso.with(getActivity()).setIndicatorsEnabled(true);
}
Picasso.with(getActivity())
.load(R.drawable.anon_user_48dp)
.transform(new CircleTransformation())
.into(imageViewStreet);
} else {
if (LogManager.isDebugable()) {
Picasso.with(getActivity()).setIndicatorsEnabled(true);
}
Picasso.with(getActivity())
.load(placeDetails.url)
.transform(new CircleTransformation())
.into(imageViewStreet);
}
return mRootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
}
#OnClick(R.id.btn_place_dialog_ok)
public void onSearchClicked() {
if (mShowPlaceListener != null) {
mShowPlaceListener.onShowPlace(place);
}
dismiss();
}
#OnClick(R.id.btn_place_dialog_cancel)
public void onCancelClicked() {
dismiss();
}
private void setPlace(BasePlace place) {
this.place = place;
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
This is the creation
GooglePlaceDetailsDialogFragment dialog = GooglePlaceDetailsDialogFragment.newInstance(item);
dialog.setTargetFragment(this, 0);
DialogUtils.showDialogFragment(getFragmentManager(), dialog);
Util..
public class DialogUtils {
private static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment,
String fragmentTag, boolean onlyIfNotDuplicate) {
// If only showing non duplicates dialogs, make sure the fragment isn't already in the manager
boolean doesFragmentExist = fragmentManager.findFragmentByTag(fragmentTag) != null;
if (!(onlyIfNotDuplicate && doesFragmentExist)) {
dialogFragment.show(fragmentManager, fragmentTag);
}
return fragmentTag;
}
public static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment,
boolean onlyIfNotDuplicate) {
return showDialogFragment(fragmentManager, dialogFragment, generateFragmentTag(dialogFragment), onlyIfNotDuplicate);
}
private static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment,
String fragmentTag) {
return showDialogFragment(fragmentManager, dialogFragment, fragmentTag, true);
}
public static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment) {
return showDialogFragment(fragmentManager, dialogFragment, generateFragmentTag(dialogFragment));
}
private static String generateFragmentTag(Fragment fragment) {
return fragment.getClass().getName();
}
}

ok when I replace the srcCompat:src= with app:srcCompat=` the images show, Strange that AS did not complain abut this typo

Related

How to Retrieve Data from Firebase Realtime Database in Fragment?

This is how my Database look like:
I already write my code inside fragment and have an error like this
java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
this is my Fragment.xml
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#drawable/gradient_hijau_kuning_kotak"
app:layout_constraintTop_toTopOf="parent" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/tampilanFoto"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginTop="88dp"
android:src="#drawable/fotorumahsakit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tampilanNamaUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="#font/swansea_bold"
android:gravity="center"
android:text="Nama User"
android:textColor="#color/black"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tampilanFoto" />
<TextView
android:id="#+id/tampilanLokasiUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="#font/twentycenth"
android:gravity="center"
android:text="Lokasi"
android:textColor="#color/black"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tampilanNamaUser" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#id/tampilanLokasiUser">
<TextView
android:id="#+id/infoAkunText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/swansea_bold"
android:text="Info Akun"
android:textColor="#color/black"
android:textSize="30sp"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:padding="20dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/iconProfile"
android:layout_width="80dp"
android:layout_marginStart="20dp"
android:layout_height="80dp"
android:src="#drawable/man"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:fontFamily="#font/swansea_bold"
android:text="Status :"
android:textColor="#color/black"
android:textSize="18sp"/>
<TextView
android:id="#+id/showStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:fontFamily="#font/swansea_thin"
android:text="status"
android:textColor="#color/black"
android:textSize="18sp"/>
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/gantiPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/twentycenth"
android:layout_gravity="center"
android:gravity="center"
android:text="GANTI PASSWORD"
android:textColor="#color/hijau_cerah"
android:textSize="18sp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is my Fragment.java
public class ProfileFragment extends Fragment {
TextView tampilanNamaUser, tampilanLokasi, statusUser, gantiPassword;
FirebaseAuth mAuth;
SessionManager sessionManager;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://simande-4f3e2-default-rtdb.firebaseio.com/");
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public ProfileFragment() {
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
//Hook
tampilanNamaUser = v.findViewById(R.id.tampilanNamaUser);
tampilanLokasi = v.findViewById(R.id.tampilanLokasiUser);
statusUser = v.findViewById(R.id.showStatus);
gantiPassword = v.findViewById(R.id.gantiPassword);
sessionManager = new SessionManager(getContext(), SessionManager.SESSION_USERSESSION);
HashMap<String, String> usersDetails = sessionManager.getUsersDetailFromSession();
String getName = usersDetails.get(SessionManager.KEY_USERNAME);
getUserInfo(getName);
return v;
}
private void getUserInfo(String getName) {
databaseReference.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
if (snapshot.hasChild(getName)){
String nama = snapshot.child("Nama").getValue().toString();
tampilanNamaUser.setText(nama);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
P.s : This is my CreateAccountActivity I put getName String on this Activity but I didn't know how to call it in another Fragment.
public class BuatAkunActv extends AppCompatActivity {
private EditText userInput, passInput;
private Button buttonRegist;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://simande-4f3e2-default-rtdb.firebaseio.com/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buat_akun_actv);
//Hook
userInput = findViewById(R.id.daftarUser);
passInput = findViewById(R.id.daftarPassword);
buttonRegist = findViewById(R.id.buttonDaftar);
buttonRegist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getName = userInput.getText().toString();
String getPassword = passInput.getText().toString();
databaseReference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild(getName)){
Toast.makeText(BuatAkunActv.this, "User sudah terdaftar", Toast.LENGTH_SHORT).show();
}
else {
databaseReference.child("Users").child(getName).child("nama").setValue(getName);
databaseReference.child("Users").child(getName).child("password").setValue(getPassword);
Toast.makeText(BuatAkunActv.this, "User berhasil dibuat", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
}
There are quite a few problems in your getUserInfo. I'm not sure if they cause the error, but here's what I'd change it to:
private void getUserInfo(String getName) {
databaseReference.child("Users").child(getName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String nama = snapshot.child("Nama").getValue().toString();
tampilanNamaUser.setText(nama);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
}
The significant change:
Instead of loading the entire Users node to check if one child exists in it, load only that child node.
Don't ignore errors in onCancelled, as it makes debugging much harder.

Expandable Recycler view doesnt show my items

I want to use an expandableRecyler but when i use the adapter it doesnt work. It doesnt give me any error or anything. just doesnt appear on the screen
I have this Fragment where i call the recyclerView
public class RecFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
Button btaddrec;
Dialog alerta;
View v;
RecyclerView rvRec;
public RecFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RecFragment.
*/
// TODO: Rename and change types and number of parameters
public static RecFragment newInstance(String param1, String param2) {
RecFragment fragment = new RecFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_rec, container, false);
rvRec = v.findViewById(R.id.recyclerviewRec);
btaddrec = (Button) v.findViewById(R.id.btaddRec);
initData();
setRecycler();
btaddrec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), MainActivity.listarec.size() + "", Toast.LENGTH_SHORT).show();
}
});
return v;
}
private void setRecycler(){
RecyclerRec recyclerRec = new RecyclerRec(MainActivity.listarec);
rvRec.setLayoutManager(new LinearLayoutManager(getActivity()));
rvRec.setAdapter(recyclerRec);
rvRec.setHasFixedSize(true);
}
private void initData(){
MainActivity.listarec.add(new Recordatorio("Homework","Math and Science Homewowk","14:00"));
MainActivity.listarec.add(new Recordatorio("Homework","Math and Science Homewowk","14:00"));
}
}
Function initData add some objects to my list (i have checked that it works with the Button, my list has 2 items)
Function setRecycler set the adapter for the recyclerview
This is my class RecyclerRec
public class RecyclerRec extends RecyclerView.Adapter<RecyclerRec.RecVh>{
ArrayList<Recordatorio> listarec;
public RecyclerRec (ArrayList<Recordatorio> lista){
this.listarec = lista;
}
#NonNull
#Override
public RecVh onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rec_layout,parent,false);
return new RecVh(v);
}
#Override
public void onBindViewHolder(#NonNull RecVh holder, int position) {
Recordatorio rec = listarec.get(position);
holder.tvTitulo.setText(rec.getTitulo());
holder.tvCuerpo.setText(rec.getCuerpo());
holder.tvHora.setText(rec.getHora());
boolean expanded = rec.isExpanded();
holder.expandable.setVisibility(expanded ? View.VISIBLE : View.GONE);
}
#Override
public int getItemCount() {
return listarec.size();
}
public class RecVh extends RecyclerView.ViewHolder {
TextView tvTitulo,tvCuerpo,tvHora;
LinearLayout linearLayout;
ConstraintLayout expandable;
public RecVh(#NonNull View itemView) {
super(itemView);
tvTitulo = itemView.findViewById(R.id.tvTituloRec);
tvCuerpo = itemView.findViewById(R.id.tvCuerpo);
tvHora = itemView.findViewById(R.id.tvHoraRec);
linearLayout = itemView.findViewById(R.id.linearlayotuexpand);
expandable = itemView.findViewById(R.id.expandableRec);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Recordatorio rec = listarec.get(getAdapterPosition());
rec.setExpanded(!rec.isExpanded());
notifyItemChanged(getAdapterPosition());
}
});
}
}
}
XML of fragment
<FrameLayout 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=".Fragments.ClasesFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewRec"
android:layout_width="match_parent"
android:layout_height="451dp"
android:layout_marginTop="50dp" />
<Button
android:id="#+id/btaddRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="160dp"
android:layout_marginTop="520dp"
android:text="Añadir" />
(Framelayout tag is closed correctly, dunno why stackoverflow doesnt write it with ctrl+k)
XML of my item/row
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tvTituloRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:padding="10dp"
android:text="Titulo Recordatorio"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#android:color/black"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvHoraRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hora"
android:textSize="17dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/expandableRec"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tvTituloRec">
<TextView
android:id="#+id/tvCuerpo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="Cuerpo del recordatorio"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
All seems to be in order but when i run the app it doesnt appear and doesnt give me any error.

RecyclerView items inside BottomSheetDialogFragment need double touch after fast scrolling

I have a RecyclerView inside BottomSheetDialogFragment. The RecyclerView items touch working normally when it's scrolling slowly.
But when the RecyclerView is scrolled fast and after the list stops (without touching), than touching on any item doesn't work on fast touch. It needs double touching.
See in the below example gif, when touching on Andhra Pradesh it's working fine. After slow scrolling, touching on Haryana also works fine. Then doing a fast scroll and touching on Punjab doesn't work on the first touch. Touching again it works.
Following is the code:
OperatorListDialogFragment.java
package com.*;
import *;
public class OperatorListDialogFragment extends BottomSheetDialogFragment{
private static final String ARG_NAME = "item_name";
private static final String ARG_LOGO = "item_logo";
private Listener mListener;
private String header;
private Context mContext;
public static OperatorListDialogFragment newInstance(String[] name, int[] logo, String header) {
final OperatorListDialogFragment fragment = new OperatorListDialogFragment();
final Bundle args = new Bundle();
args.putStringArray(ARG_NAME, name);
args.putIntArray(ARG_LOGO, logo);
args.putString("header", header);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_operator_list_dialog_list_dialog, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
TextView headerTV = view.findViewById(R.id.title);
headerTV.setText(getArguments().getString("header"));
final RecyclerView recyclerView = view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new OperatorAdapter(getArguments().getStringArray(ARG_NAME), getArguments().getIntArray(ARG_LOGO)));
view.findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
final Fragment parent = getParentFragment();
if (parent != null) {
mListener = (Listener) parent;
} else {
mListener = (Listener) context;
}
}
#Override
public void onDetach() {
mListener = null;
super.onDetach();
}
public interface Listener {
void onFilterSelected(String selected, String selectedQuery);
}
private class ViewHolder extends RecyclerView.ViewHolder {
final TextView text;
ImageView logo;
ViewHolder(LayoutInflater inflater, ViewGroup parent) {
// TODO: Customize the item layout
super(inflater.inflate(R.layout.fragment_operator_list_dialog_list_dialog_item, parent, false));
text = itemView.findViewById(R.id.tv_operator_name);
logo = itemView.findViewById(R.id.iv_recharge_provider_icon);
}
}
private class OperatorAdapter extends RecyclerView.Adapter<ViewHolder> {
private String[] mNames;
private int[] mLogos;
OperatorAdapter(String[] name, int[] logo) {
mNames = name;
mLogos = logo;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.text.setText(mNames[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("clicked", "" + position);
}
});
}
#Override
public int getItemCount() {
return mNames.length;
}
}
}
dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<ImageView
android:focusable="true"
android:clickable="true"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="Close"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:id="#+id/dismiss"
android:padding="14dp"
android:src="#drawable/ic_close_black_24dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/title"
app:layout_constraintTop_toTopOf="#id/dismiss"
app:layout_constraintBottom_toBottomOf="#id/dismiss"
app:layout_constraintLeft_toRightOf="#id/dismiss"
android:padding="14dp"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
tools:text="Select operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<View
app:layout_constraintTop_toBottomOf="#id/dismiss"
android:background="#969696"
android:layout_width="match_parent"
android:layout_height="0.5dp"/>
<androidx.recyclerview.widget.RecyclerView
app:layout_constraintTop_toBottomOf="#id/dismiss"
app:layout_constraintBottom_toBottomOf="parent"
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
app:layout_constrainedHeight="true"
android:paddingTop="#dimen/list_item_spacing_half"
android:paddingBottom="#dimen/list_item_spacing_half"
tools:context=".fragments.OperatorListDialogFragment"
tools:listitem="#layout/fragment_operator_list_dialog_list_dialog_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:gravity="center_vertical"
android:orientation="horizontal"
android:id="#+id/ll_operator_list_wrapper"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:visibility="gone"
android:layout_marginLeft="16dp"
android:id="#+id/iv_recharge_provider_icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginVertical="16dp"
android:layout_centerVertical="true"
android:src="#drawable/ic_bsnl_logo"
tools:visibility="visible"/>
<TextView
android:padding="16dp"
android:textColor="#212121"
android:textSize="14sp"
android:ellipsize="end"
android:id="#+id/tv_operator_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text="BSNL"
android:layout_toRightOf="#+id/iv_recharge_provider_icon"
android:layout_centerInParent="true"/>
<View
android:layout_below="#id/iv_recharge_provider_icon"
android:id="#+id/divider0"
android:background="#eeeeee"
android:visibility="visible"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/iv_recharge_provider_icon"
/>
</RelativeLayout>
add android:nestedScrollingEnabled="false" in RecyclerView

Fragment TextView is not able to be updated from parcelable object

In my fragment, I have a textView which I want to set to a specific String. I want to get the String for the textView from an object, which I send to the fragment as a parcelable.
I can retrieve the parcelable object and use the object to get the String (when I log it, the correct String is displayed). But when I want to use this to set the textView, the textView doesn't change.
Any ideas why this happens and how I can fix it?
Thanks!
Edit1: I added the activity the fragment is located in to, maybe the error is here?
Edit2: I added the Data class (the parcelable object). But removed the content of the constructor just to keep it easy to read.
public class NavigationFragment extends Fragment {
private static final String TAG = "NavigationFragment";
public NavigationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle = this.getArguments();
if(bundle!=null) {
Data data = (Data) bundle.getParcelable("data");
TextView stopTitle = (TextView) view.findViewById(R.id.stopTitle);
final String name = data.getTourName();
Log.d(TAG, name);
stopTitle.setText(name);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context=".DoTourActivity">
<TextView
android:id="#+id/stopTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="stopTitle"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="365dp"
android:layout_height="158dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.492"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/stopTitle"
tools:src="#drawable/placeholder_pic" />
<TextView
android:id="#+id/stopDescription"
android:layout_width="384dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="24dp"
android:text="stopDescriptionstopDescriptionstopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescriptionstopDescriptionstopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="395dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/stopDescription">
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#android:drawable/ic_menu_mylocation" />
<TextView
android:id="#+id/locationAdress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="locationAdress"
android:textSize="23dp" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#android:drawable/ic_dialog_map" />
</LinearLayout>
<EditText
android:id="#+id/pincode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:ems="10"
android:inputType="number"
android:text="pincode"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout" />
<Button
android:id="#+id/confirmButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="confirm"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pincode" />
</android.support.constraint.ConstraintLayout>
public class DoTourActivity extends AppCompatActivity {
private static final String TAG = "DoTourActivity";
private SectionStatePagerAdapter sectionStatePagerAdapter;
private ViewPager viewPager;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_tour);
//Fragment management
sectionStatePagerAdapter = new SectionStatePagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
//Setup actionbar
Toolbar myToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(myToolbar);
//get chosen location & build tour
Fragment fragment = new NavigationFragment();
String location = getIntent().getStringExtra("location");
Bundle bundle = new Bundle();
Data data = new Data(location);
bundle.putParcelable("data", data);
fragment.setArguments(bundle);
//launch fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.commit();
}
public void setupViewPager (ViewPager viewPager) {
SectionStatePagerAdapter adapter = new SectionStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new NavigationFragment(), "navFragment");
adapter.addFragment(new QuestionFragment(), "qesFragment");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// switch(item.getItemId())
return super.onOptionsItemSelected(item);
}
}
public class Data implements Parcelable {
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Data createFromParcel(Parcel in) {
return new Data(in);
}
public Data[] newArray(int size) {
return new Data[size];
}
};
private String tourName;
int tourID;
int possiblePoints;
int stops;
Spot[] spots;
//while playing tour
int points = 0;
// Constructor
public Data(String tour){
}
public String getTourName() {
return tourName;
}
public void setTourName(String tourName) {
this.tourName = tourName;
}
public int getTourID() {
return tourID;
}
public void setTourID(int tourID) {
this.tourID = tourID;
}
public int getPossiblePoints() {
return possiblePoints;
}
public void setPossiblePoints(int possiblePoints) {
this.possiblePoints = possiblePoints;
}
public int getStops() {
return stops;
}
public void setStops(int stops) {
this.stops = stops;
}
public Spot[] getSpots() {
return spots;
}
public void setSpots(Spot[] spots) {
this.spots = spots;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
// Parcelling part
public Data(Parcel in){
this.tourName = in.readString();
this.tourID = in.readInt();
this.possiblePoints = in.readInt();
this.stops = in.readInt();
this.spots = in.createTypedArray(Spot.CREATOR);
this.points = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.tourName);
dest.writeInt(this.tourID);
dest.writeInt(this.possiblePoints);
dest.writeInt(this.stops);
for(Spot s : spots){
dest.writeParcelable(s, flags);
}
dest.writeInt(this.points);
}
}
Thanks to #Mike M. this is solved.
The problem was with the activity in which the fragments were hosted. In there I created two different NavigationFragments which I added to the activity. The updating of the TextView happen on the wrong one.
I see from another answer that there was a problem with fragment instances, but I believe you also have a problem with your Parcelable implementation.
public Data(Parcel in){
...
this.spots = in.createTypedArray(Spot.CREATOR);
...
}
#Override
public void writeToParcel(Parcel dest, int flags) {
...
for(Spot s : spots){
dest.writeParcelable(s, flags);
}
...
}
These two calls need to be mirrored, and they currently are not. Rather than iterating over the array yourself, you should use the writeTypedArray() method:
public Data(Parcel in){
...
this.spots = in.createTypedArray(Spot.CREATOR);
...
}
#Override
public void writeToParcel(Parcel dest, int flags) {
...
dest.writeTypedArray(spots, flags);
...
}
If you look at the implementations for writeTypedArray() and createTypedArray(), you'll see that part of the work is to write a flag that indicates the size of the array, so that the code knows how many instances to read out on the other side. Your implementation does not include this step, so the two will be incompatible.

the application closes onBackPressed in main activity

Hello i am new to fragments.. I have one main activity and two fragments in it. if i enter data in first fragment's editText , it is displayed on second Fragment's TextView.. If i enter the data and press submit button repeatedly, the data is changing in second fragment too.. but when i press back button, the application get closed. I want to display data that was previously entered by me in fragment when i press the back button
Here is the code:
FirstFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private EditText inputName;
private EditText inputPhone;
private String userName;
private String userPhone;
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
inputName = (EditText) view.findViewById(R.id.edit_text_name);
inputPhone = (EditText) view.findViewById(R.id.edit_text_phone);
TextView submit = (TextView) view.findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputName.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Name must be filled", Toast.LENGTH_LONG).show();
return;
}
else if(inputPhone.getText().toString().equals("")){
Toast.makeText(getActivity(),"please enter the phone number" , Toast.LENGTH_SHORT).show();
return;
}
userName = inputName.getText().toString();
userPhone = inputPhone.getText().toString();
onButtonPressed(userName, userPhone);
inputName.setText("");
inputPhone.setText("");
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String nameContent, String phoneContent) {
if (mListener != null) {
mListener.onFragmentInteraction(nameContent, phoneContent);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String nameContent, String phoneContent);
}
}
SecondFragment extends Fragment {
//private OnFragmentInteractionListener mListener;
private TextView updateName;
private TextView updatePhone;
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_second, container, false);
updateName = (TextView)view.findViewById(R.id.text_view_name);
updatePhone = (TextView)view.findViewById(R.id.text_view_phone);
return view;
}
public void updateTextField(String name, String phone){
updateName.setText(name);
updatePhone.setText(phone);
}
}
MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener{
private FragmentActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onFragmentInteraction(String nameContent, String phoneContent) {
SecondFragment secondFragment = (SecondFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_show);
secondFragment.updateTextField(nameContent, phoneContent);
}
public FragmentActivity getActivity() {
return activity;
}
}
**fragment_first.xml**
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">
<EditText
android:id="#+id/edit_text_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/enter_name"
android:inputType="text"
android:paddingEnd="5dp"
android:paddingStart="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintLeft_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.050" />
<EditText
android:id="#+id/edit_text_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/enter_phone"
app:layout_constraintTop_toBottomOf="#+id/edit_text_name"
android:inputType="phone"
android:paddingTop="25dp"
android:paddingStart="5dp"
android:paddingEnd="5dp"/>
<TextView
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/edit_text_phone"
android:layout_marginTop="50dp"
android:padding="7dp"
android:text="#string/sbmt"
android:textSize="20sp"
android:textColor="#color/colorAccent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="#drawable/button_stroke"/>
</android.support.constraint.ConstraintLayout>
**fragment_Second.xml**
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">
<TextView
android:id="#+id/text_view_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:textSize="30sp"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:id="#+id/text_view_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/text_view_name"
android:textSize="20sp"
android:padding="8dp"
android:textColor="#color/colorPrimary"/>
</android.support.constraint.ConstraintLayout>
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">
<fragment
android:id="#+id/fragment_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.seasiainfotech.singhjasmeet.passinfragments.fragments.FirstFragment"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
<fragment
android:id="#+id/fragment_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.seasiainfotech.singhjasmeet.passinfragments.fragments.SecondFragment"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/fragment_input"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Override "onBackPressed" method in MainActivity
#Override
public void onBackPressed()
{
if(want_to_close_the_app){
//call super
super.onBackPressed();
}
else{
// dont call super
}
}
Give your fragments tags while adding them. Ex. Tag for FirstFragment is "firstFragment" and tag for SecondFragment is "secondFragment". Take a common String variable called current fragment in your activity and change it while adding fragment.
public class MainActivity extends Activity{
public static String currentFragment = null;
//while adding first fragment
currentFragment = "firstFragment";
//while adding second fragment
currentFragment = "firstFragment";
}
Now override onBackPressed in your activity as below.
#Override
public void onBackPressed() {
if(currentFragment.equals("secondFragment"){
//load first fragment
}else{
super.onBackPressed();
}
}
override onBackPressed method.
#Override
public void onBackPressed()
{
super.onBackPressed();// remove this line
...
//enter your code here.
}
and add this code.
getSupportFragmentManger().
beginTransaction().
replace().
addToBackStack().
.commit();

Categories

Resources