I have an activity with multiple steps, each step being a fragment transaction with an edittext box, with a next/back button to navigate and initiate sending the users input data. I want to be able to move throughout the fragments with the text in each box staying static. I can move back no problem, but as soon as I click next the next fragment is recreated and everything is lost.
I tried:
using a dummy view in onCreateView
refetching the string in onCreate
setRetainInstance(true); in the constructor
Using a viewpager has other complications regarding receiving data which I was not able to solve despite many here attempting to help, so I have no choice but to use fragment transactions in my app.
main/FormActivity.java
package com.loopbreakr.formproject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class FormActivity extends AppCompatActivity implements PageOne.ExitFormInteractionListener{
//DECLARE COMPONENTS
private FrameLayout fragmentContainer;
private Button backToMain;
private Button startForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//FIND COMPONENTS IN XML
setContentView(R.layout.activity_form);
fragmentContainer = findViewById(R.id.frame_layout);
backToMain = findViewById(R.id.return_button);
startForm = findViewById(R.id.start_button);
//SET LISTENERS/INTENTS FOR BUTTONS
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
startForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragments();
}
});
}
private void openFragments() {
PageOne fragment1 = PageOne.newInstance();
FragmentManager fragmentManager =getSupportFragmentManager();
FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
beginTransaction.addToBackStack(null);
beginTransaction.add(R.id.frame_layout,fragment1,"PageOne_tag");
beginTransaction.commit();
}
#Override
public void onFragmentInteraction(String answerOneText) {
}
}
One of my fragments PageOne.java
package com.loopbreakr.formproject;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class PageOne extends Fragment {
View restored;
private static final String SAVED = "text";
private String savedText;
private String answerOneString;
private EditText answerOne;
private ExitFormInteractionListener mListener;
public PageOne() {
setRetainInstance(true);
}
public static PageOne newInstance() {
PageOne fragment = new PageOne();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
savedText = getArguments().getString(SAVED);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(restored == null){
restored = inflater.inflate(R.layout.fragment_page_one, container, false);
}
answerOne = restored.findViewById(R.id.answer_one);
Button exitForm = restored.findViewById(R.id.exit_form);
Button goNextTwo = restored.findViewById(R.id.gonext_two);
exitForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
returnToDesc();
}
});
goNextTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answerOneString = answerOne.getText().toString();
sendToTwo(answerOneString);
openSecondFragment();
}
});
return restored;
}
private void sendToTwo(String answerOneText) {
if(mListener != null){
mListener.onFragmentInteraction(answerOneText);
}
}
private void openSecondFragment() {
PageTwo fragment2 = PageTwo.newInstance(answerOneString);
FragmentTransaction fragTransition = getFragmentManager().beginTransaction();
fragTransition.replace(R.id.frame_layout, fragment2,"PageTwo_TAG");
fragTransition.addToBackStack(null);
fragTransition.commit();
}
private void returnToDesc(){
FragmentManager fragTransBack = getFragmentManager();
fragTransBack.popBackStack();
}
public interface ExitFormInteractionListener{
void onFragmentInteraction(String answerOneText);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof ExitFormInteractionListener) {
mListener = (ExitFormInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
activity_form.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FormActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="32dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</LinearLayout>
<TextView
android:id="#+id/activity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/activity_title"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/return_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="#string/return_text"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/start_text"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
activity_page_one.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
tools:context=".PageOne"
android:focusable="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="#+id/activity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/activity_title"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<Button
android:id="#+id/exit_form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="#string/back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/gonext_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:stateListAnimator="#null"/>
<EditText
android:id="#+id/answer_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="start|top"
android:hint="#string/answer_one_hint"
android:inputType="textMultiLine|textAutoCorrect"
android:maxLines="4"
android:minLines="4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/activity_name"
android:stateListAnimator="#null"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Thanks.
Related
Hi I've been trying to make a pop up window which presents a trackable seekbar as a part of a school project, both parts of the code work alone but when put together the seekbar progress is not tracked (you can move the seekbar but the number won't change), Help would be very appreciated!
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonShowPopupWindowClick(View view) {
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.activity_pop_up, null);
// create the popup window
int width = LinearLayout.LayoutParams.MATCH_PARENT;
int height = 500;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
// show the popup window
// which view you pass in doesn't matter, it is only used for the window token
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
}
}
activity_main.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_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButtonShowPopupWindowClick"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.368" />
</androidx.constraintlayout.widget.ConstraintLayout>
popUp.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
public class popUp extends AppCompatActivity {
private TextView textView;
private SeekBar seekBar;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressBar.setProgress(progress);
textView.setText("" + progress + "$");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
activity_pop_up.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right">
<Button
android:id="#+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="confirm"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.06"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.01999998" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="250dp"
android:layout_height="55dp"
android:progress="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.78"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.01999998" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView3"
android:layout_width="154dp"
android:layout_height="45dp"
android:gravity="center"
android:text="amount:"
android:textSize="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.110000014" />
<TextView
android:id="#+id/textView"
android:layout_width="214dp"
android:layout_height="44dp"
android:text="0"
android:textSize="30dp"
android:gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.75"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.110000014" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/seekBar"
android:layout_alignParentStart="true"
android:layout_marginBottom="21dp" />
</LinearLayout>
On the main screen I have 7 buttons (days) and a fragment.
For every day of the week I wanted to generate a fragment with some EditTexts and a ListView, but creating 7 fragments with the same layout and almost the same class content seems too repetitive.
I only did it for Monday and Tuesday.
The only difference between MondayFragment and TuesdayFragment is that in TuesdayFragment I renamed the variable mondayTV to tuesdayTV and in layout I changed the ids of the submit button and the ListView. Also the key for Bundle is different. I don't think it's worth posting it since it's so similar to MondayFragment.
I want to know if it's possible to create a fragment template and use it to generate a fragment for every button of the activity given this code I wrote. There is still a lot to work on when it comes to functionality but I can't get this idea out of my head.
MainActivity.java
package com.example.dietmanagement;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button monday, tuesday, wednesday, thursday, friday, saturday, sunday;
final MondayFragment mondayFragment = new MondayFragment();
final TuesdayFragment tuesdayFragment = new TuesdayFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Intent i = getIntent();
String current_user = i.getStringExtra("current_user");
TextView current_user_txtview = findViewById(R.id.current_user);
current_user_txtview.setText("Welcome, " + current_user);*/
monday = (Button)findViewById(R.id.monday_btn);
tuesday = (Button)findViewById(R.id.tuesday_btn);
wednesday = (Button)findViewById(R.id.wednesday_btn);
thursday = (Button)findViewById(R.id.thursday_btn);
friday = (Button)findViewById(R.id.friday_btn);
saturday = (Button)findViewById(R.id.saturday_btn);
sunday = (Button)findViewById(R.id.sunday_btn);
monday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(mondayFragment);
getDay(mondayFragment, "monday", (String) monday.getContentDescription());
}
});
tuesday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(tuesdayFragment);
getDay(tuesdayFragment, "tuesday", (String) tuesday.getContentDescription());
}
});
}
private void openFragment(final Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.daysfragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void getDay(final Fragment fragment, String key, String value)
{
Bundle bnd = new Bundle();
bnd.putString(key, value);
fragment.setArguments(bnd);
}
}
Activity_main.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_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green"
tools:context=".MainActivity">
<Button
android:id="#+id/tuesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/tuesday_context"
android:text="#string/tuesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.194"
app:layout_constraintStart_toEndOf="#+id/monday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<TextView
android:id="#+id/main_title"
android:layout_width="147dp"
android:layout_height="93dp"
android:fontFamily="sans-serif-medium"
android:text="#string/welcome_label"
android:textColor="#FFFFFF"
android:textSize="70sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.414"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.049" />
<Button
android:id="#+id/monday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/monday_context"
android:text="#string/monday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<Button
android:id="#+id/thursday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/thursday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.018"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/sunday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/sunday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.786"
app:layout_constraintStart_toEndOf="#+id/saturday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/saturday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/saturday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.225"
app:layout_constraintStart_toEndOf="#+id/friday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/friday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/friday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.137"
app:layout_constraintStart_toEndOf="#+id/thursday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/wednesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/wednesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.369"
app:layout_constraintStart_toEndOf="#+id/tuesday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<ImageView
android:id="#+id/logo"
android:layout_width="52dp"
android:layout_height="58dp"
android:layout_marginStart="8dp"
android:layout_marginTop="52dp"
android:contentDescription="#string/app_name"
app:layout_constraintStart_toEndOf="#+id/main_title"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_logo" />
<TextView
android:id="#+id/current_user"
android:layout_width="362dp"
android:layout_height="27dp"
android:text="#string/current_user"
android:textAlignment="viewEnd"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/main_title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.938"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.318" />
<FrameLayout
android:id="#+id/daysfragment"
android:layout_width="match_parent"
android:layout_height="460dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MondayFragment.java
package com.example.dietmanagement;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MondayFragment extends Fragment {
public TextView mondayTV;
public ArrayList<String> hour_food;
public ArrayAdapter<String> listViewAdapter;
public ListView listView;
public EditText input_meal;
public EditText input_time;
public Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_monday, container, false);
mondayTV = (TextView) v.findViewById(R.id.day);
Bundle bndMon = getArguments();
String day = bndMon.getString("monday");
mondayTV.setText(day);
hour_food = new ArrayList<String>();
listViewAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = (ListView)v.findViewById(R.id.monday_list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
}
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = (Button) v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if(TextUtils.isEmpty(input_meal.getText())){
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
}
else
{
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
}
});
return v;
}
}
fragment_monday.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:background="#color/background_green"
tools:context=".MondayFragment">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn_monday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/monday_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
strings.xml
Create DayFragment and layout only for one day. Pass extra information for Fragment and handle situations for different days with that extra information (in your case it looks like only String from bundle is different).
fragment_day.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
DayFragment.java
public class DayFragment extends Fragment {
private TextView dayTV;
private ArrayList<String> hour_food;
private ArrayAdapter<String> listViewAdapter;
private ListView listView;
private EditText input_meal;
private EditText input_time;
private Button submit;
private String text;
public DayFragment(String text) {
this.text = text;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_day, container, false);
dayTV = v.findViewById(R.id.day);
dayTV.setText(text);
hour_food = new ArrayList<>();
listViewAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = v.findViewById(R.id.list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener((parent, view, position, id) -> {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(v1 -> {
if (TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(input_meal.getText())) {
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
} else {
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
});
return v;
}
}
Use constructor for passing information.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button monday = findViewById(R.id.monday_btn),
tuesday = findViewById(R.id.tuesday_btn),
wednesday = findViewById(R.id.wednesday_btn),
thursday = findViewById(R.id.thursday_btn),
friday = findViewById(R.id.friday_btn),
saturday = findViewById(R.id.saturday_btn),
sunday = findViewById(R.id.sunday_btn);
openFragment(monday);
openFragment(tuesday);
openFragment(wednesday);
openFragment(thursday);
openFragment(friday);
openFragment(saturday);
openFragment(sunday);
}
private void openFragment(Button btn) {
btn.setOnClickListener(v -> {
String contentDescription = btn.getContentDescription().toString();
getSupportFragmentManager().beginTransaction()
.replace(R.id.daysfragment, new DayFragment(contentDescription))
.addToBackStack(null)
.commit();
});
}
}
In MainActivity openFragment() method takes a Button parameter and with that Button and sets onClickListener to that Button. When you click any Button it gets content description from that Button and passing it to Fragment and opens that Fragment with that content description.
I recently learned about Fragments in Android and was building a notepad application to practice them.
Idea: The idea behind the app is simple. I press the button to add a new note. A CardView Viewgroup turns visible. The fragment will be housed within this CardView.
Problem: When I press the button to add a new note, the fragment does not pop up.
MainActivity.java
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Objects;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private CardView fragmentCardView;
private Button newNoteButton;
private FragmentManager fragmentManager = getSupportFragmentManager();
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setActionBar();
newNoteButton = findViewById(R.id.new_note_button);
fragmentCardView = findViewById(R.id.fragment_cardView);
}
void setActionBar(){
Objects.requireNonNull(getSupportActionBar()).setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.layout_custom_action_bar);
}
void showCreateNoteFragment(){
CreateNoteFragment createNoteFragment = CreateNoteFragment.newInstance();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_cardView, createNoteFragment);
fragmentTransaction.commit();
fragmentCardView.setVisibility(View.VISIBLE);
}
#Override
public void onClick(View v) {
if (v == newNoteButton)
showCreateNoteFragment();
}
}
activity_main.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_width="match_parent"
android:layout_height="match_parent"
android:background="#F2F2F2"
tools:context=".MainActivity">
<ListView
android:id="#+id/notes_listView"
android:layout_width="match_parent"
android:layout_height="667dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<Button
android:id="#+id/new_note_button"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_marginTop="27dp"
android:fontFamily="#font/nunito_bold"
android:text="#string/new_note_button_string"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/notes_listView"/>
<androidx.cardview.widget.CardView
android:id="#+id/fragment_cardView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginBottom="100dp"
android:layout_marginStart="25dp"
android:layout_marginEnd="25dp"
android:visibility="invisible"/>
</androidx.constraintlayout.widget.ConstraintLayout>
CreateNoteFragment.java
package com.example.notepadapplication;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class CreateNoteFragment extends Fragment implements View.OnClickListener {
private EditText inputEditText;
public CreateNoteFragment() {
// Required empty public constructor
}
static CreateNoteFragment newInstance(){
return new CreateNoteFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create_note, container, false);
inputEditText = rootView.findViewById(R.id.input_editText);
Button saveButton = rootView.findViewById(R.id.save_button);
saveButton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
String saveButtonText = inputEditText.getText().toString();
}
}
fragment_create_note.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginTop="100dp"
android:layout_marginBottom="100dp"
android:layout_marginStart="25dp"
android:layout_marginEnd="25dp"
android:background="#F2F2F2"
tools:context=".CreateNoteFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/header_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/display_fragment_header_string"
android:layout_marginTop="10dp"
android:textAlignment="center"
android:textSize="20sp"
android:fontFamily="#font/nunito_bold"/>
<View
android:id="#+id/divider_view"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_below="#id/header_textView"
android:background="#000000" />
<EditText
android:id="#+id/input_editText"
android:layout_width="match_parent"
android:layout_height="475dp"
android:layout_below="#id/divider_view"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:padding="10dp"
android:inputType="textMultiLine"
android:gravity="top"
android:background="#FFFFFF"
tools:ignore="Autofill,LabelFor,TextFields" />
<Button
android:id="#+id/save_button"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="#string/save_button_string"
android:fontFamily="#font/nunito_bold"/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Could anyone check why the fragment isn't popping up? Thanks for the help, guys.
P.S.: I think that the application might become a little bloated because of all the ViewGroups that I'm using. If you guys have a better way to design this, by all means, I would love any input.
When I press the button to add a new note, the fragment does not pop up.
This is expected since your button doesn't know what to do when pressed.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setActionBar();
newNoteButton = findViewById(R.id.new_note_button);
// Button will call activity's onClick whenever it's clicked
newNoteButton.setOnClickListener(this);
fragmentCardView = findViewById(R.id.fragment_cardView);
}
My Android app is composed of an SQLite database which populates individual ListView items with data user saves. Those items are available for display in activity_main.xml.
I have a class called RecordsListFragment which contains the two problematic methods: onItemClick and onItemLongClick. Here is the class in its entirety:
package com.example.benignfella.projectworkinghoursapplication.Fragment;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.example.benignfella.projectworkinghoursapplication.R;
import com.example.benignfella.projectworkinghoursapplication.Adapter.RecordsListAdapter;
import com.example.benignfella.projectworkinghoursapplication.Database.RecordsDAO;
import com.example.benignfella.projectworkinghoursapplication.GetSet.Records;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class RecordsListFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener {
public static final String ARGUMENT_ITEM_ID = "records_list";
Activity activity;
ListView recordsListView;
ArrayList<Records> records;
RecordsListAdapter recordsListAdapter;
RecordsDAO recordsDAO;
private GetRecordsTask task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
recordsDAO = new RecordsDAO(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_records_list, container, false);
findViewsById(view);
task = new GetRecordsTask(activity);
task.execute((Void) null);
return view;
}
private void findViewsById(View view) {
recordsListView = (ListView) view.findViewById(R.id.list_records);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Records record = (Records) parent.getItemAtPosition(position);
if (records != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedRecord,", record);
CustomRecordsDialogFragment customRecordsDialogFragment = new CustomRecordsDialogFragment();
customRecordsDialogFragment.setArguments(arguments);
customRecordsDialogFragment.show(getFragmentManager(), CustomRecordsDialogFragment.ARGUMENT_ITEM_ID);
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Records records = (Records) parent.getItemAtPosition(position);
recordsDAO.deleteRecord(records);
recordsListAdapter.remove(records);
return true;
}
public class GetRecordsTask extends AsyncTask<Void, Void, ArrayList<Records>> {
private final WeakReference<Activity> activityWeakRef;
public GetRecordsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected ArrayList<Records> doInBackground(Void... arg0) {
ArrayList<Records> recordsArrayList = recordsDAO.getRecords();
return recordsArrayList;
}
#Override
protected void onPostExecute(ArrayList<Records> empList) {
if (activityWeakRef.get() != null && !activityWeakRef.get().isFinishing()) {
records = empList;
if (empList != null) {
if (empList.size() != 0) {
recordsListAdapter = new RecordsListAdapter(activity, empList);
recordsListView.setAdapter(recordsListAdapter);
} else {
Toast.makeText(activity, "No Records about records... wait wot m8?",
Toast.LENGTH_LONG).show();
}
}
}
}
}
public void updateView() {
task = new GetRecordsTask(activity);
task.execute((Void) null);
}
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
Here is activity_main.xml with FrameLayout:
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Layout resource file which contains a ListView is called fragment_records_list.xml and here it is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f9f9f9">
<ListView
android:id="#+id/list_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay"/>
</RelativeLayout>
Lastly, there is a resource file containing the layout of a single item, list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ededed"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/layout_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_record_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="ID"
android:textSize="20dp"/>
<TextView
android:id="#+id/text_record_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/text_record_id"
android:padding="5dp"
android:text="Date"
android:textColor="#00942b"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/text_record_date"
android:drawableStart="#drawable/ic_date_range_black_24dp"
android:padding="5dp"
/>
<TextView
android:id="#+id/text_record_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_id"
android:padding="5dp"
android:text="Description"
/>
<TextView
android:id="#+id/text_record_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:padding="5dp"
android:text="17:00"
android:textSize="16dp"
android:textColor="#004561"
/>
<TextView
android:id="#+id/text_record_dash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_start"
android:padding="5dp"
android:text="-"
android:textSize="16dp"
/>
<TextView
android:id="#+id/text_record_finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_dash"
android:padding="5dp"
android:text="20:00"
android:textSize="16dp"
android:textColor="#c7002a"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_finish"
android:drawableStart="#drawable/ic_timer_black_24dp"
/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/layout_item"
android:background="#000000"
/>
</RelativeLayout>
I haven't found a definite answer to my question, so I'm asking for a bit of help here.
You need set OnItemClickListener and OnLongItemClickListener to ListView, I edited your method in the initializing variable ListView:
private void findViewsById(View view) {
recordsListView = (ListView) view.findViewById(R.id.list_records);
recordsListView.setOnItemClickListener(this);
recordsListView.setOnItemLongClickListener(this);
}
I have a fragment that contains a PercentRelativeLayout that I want to replace with another fragment on a button click. Here is the outer fragment xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.percent.PercentRelativeLayout
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:layout_widthPercent="92%"
app:layout_heightPercent="80%"
app:layout_marginTopPercent="15%">
<android.support.percent.PercentRelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Vecka 49"
android:id="#+id/weekOneTextView"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekOneTextView"
android:id="#+id/displayWeekOne">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 50"
android:id="#+id/weekTwoTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekTwoTextView"
android:id="#+id/displayWeekTwo">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 51"
android:id="#+id/weekThreeTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekThreeTextView"
android:id="#+id/displayWeekThree">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
android:layout_below="#+id/displayWeekThree"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 52"
android:id="#+id/weekFourTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekFourTextView"
android:id="#+id/displayWeekFour">
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
Here is the onClick method in the fragments Java file
private void setOnClickListeners(){
mWeekOneTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DropDownWeekFragment dropDownWeekFragment = new DropDownWeekFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.displayWeekOne, dropDownWeekFragment).commit();
}
});
I want to replace the PercentRelativeLayout with ID displayWeekOne with a fragment, here is the for the fragment I wish to replace with
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="layout.DropDownWeekFragment">
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="80%"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Måndag"
android:id="#+id/monday"
app:layout_marginTopPercent="2%"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tisdag"
android:id="#+id/tuesday"
android:layout_below="#id/monday"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/wednessday"
android:layout_below="#id/tuesday"
android:text="Onsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/thursday"
android:layout_below="#id/wednessday"
android:text="Torsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friday"
android:layout_below="#id/thursday"
android:text="Fredag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/saturday"
android:layout_below="#id/friday"
android:text="Lördag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sunday"
android:layout_below="#id/saturday"
android:text="Söndag"/>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
And here is the Java for that fragment
package layout;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.studentconsulting.mypages.R;
import static android.content.ContentValues.TAG;
public class DropDownWeekFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DropDownWeekFragment() {
// Required empty public constructor
}
public static DropDownWeekFragment newInstance(String param1, String param2) {
DropDownWeekFragment fragment = new DropDownWeekFragment();
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);
Log.d("hej", "oncreate");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_drop_down_week, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
I read in the documentation that I can use replace() to replace another fragment, but I want to replace the PercentRelativeLayout if that is possible, or add the fragment to the outer fragments xml
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.displayWeekOne, dropDownWeekFragment).commit();
You can use replace() to replace one Fragment with another Fragment, as well as a Layout with a Fragment.
Not tested. Hope it works.