How can I put a fragment inside of a tab? - java

In my Android Studio project I have a fragment that I created to display the profile page of a dating app. I also have a signUpActivity that is used in place of the mainActivity that leads to another activity called secondActivity. My fragment is called profileFragment. What I am trying to do is put the profileFragment into the first tab of my secondActivity. Right now when I run the project and create a valid dating profile I get the fragment in the background with the second activity with its tabs in the foreground. What is the easiest way to add my fragment to a tab with what I have right now? I attatched the code for the xml code and java code for the secondActivity and the profileFragment. I will also attatch a link to my github if it helps to answer my question:
https://github.com/alasali1/Form
Below is the code for my secondActivity:
package com.example.form;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.form.ui.main.SectionsPagerAdapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class SecondActivity extends AppCompatActivity {
private static final String TAG = SecondActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
//fragment
ProfileFragment profileFragment = new ProfileFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_profile, profileFragment, "profileFragment");
transaction.commit();
Log.i(TAG, "onCreate()");
//Get the bundle
Bundle bundle = getIntent().getExtras();
String stringDate = bundle.getString("date");
String stringName = bundle.getString("name");
String stringJob = bundle.getString("job");
String stringDescription = bundle.getString("description");
//set arguments
profileFragment.setArguments(bundle);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//turn date string into date object
public static Calendar convertDate(String stringDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar date = Calendar.getInstance();
date.setTime(sdf.parse(stringDate));
return date;
}
public static boolean checkAge(Calendar date){
Calendar today = Calendar.getInstance();
int checkYear = today.get(Calendar.YEAR) -18;
int yob = date.get(Calendar.YEAR);
int mob = date.get(Calendar.MONTH);
int dob = date.get(Calendar.DAY_OF_MONTH);
if(date.after(today)){
return false;
}
if(yob > checkYear){
return false;
} else if(mob > today.get(Calendar.MONTH)){
return false;
} else if(dob > today.get(Calendar.DAY_OF_MONTH)){
return false;
} else{
return true;
}
}
#Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart()");
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart()");
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
}
#Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause()");
}
#Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop()");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
}
While the java code for my fragment is :
package com.example.form;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.ParseException;
import java.util.Calendar;
public class ProfileFragment extends Fragment {
TextView textView, jobView, ageView, descriptionView;
ImageView imageView;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
String stringDate = getArguments().getString("date");
String stringName = getArguments().getString("name");
String stringJob = getArguments().getString("job");
String stringDescription = getArguments().getString("description");
//make imageView
imageView = v.findViewById(R.id.imageView);
//make textview
textView = v.findViewById(R.id.textView);
//make job textview
jobView = v.findViewById(R.id.job);
//add input to jobView
if(stringJob.equals("")){
jobView.append("N/A");
} else{
jobView.setText(stringJob);
}
//make descriptionView
descriptionView = v.findViewById(R.id.description);
//add input to descriptionView
descriptionView.append(" " +stringDescription);
//make ageView
ageView= v.findViewById(R.id.age);
//make age variable
int age = 0;
//Get age
try {
Calendar birth = ConfirmActivity.convertDate(stringDate);
Calendar today = Calendar.getInstance();
if(today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)){
age= today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) - 1;
}
else{
age= today.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
}
} catch (ParseException e) {
e.printStackTrace();
}
//set age
ageView.append(String.valueOf(age));
//convert date
try {
Calendar date = ConfirmActivity.convertDate(stringDate);
//compare date
if(ConfirmActivity.checkAge(date)){
textView.setText(" "+ stringName +" Thank you for signing up");
}
else{
imageView.equals(null);
textView.append(" Please try again when you're older");
jobView.equals("");
ageView.equals("");
}
} catch (ParseException e) {
e.printStackTrace();
}
return v;
}
}
The XML for my second activity is :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".SecondActivity">
<FrameLayout
android:id="#+id/fragment_profile"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.Form.AppBarOverlay">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
While the xml for the fragment is :
<?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"
tools:context=".ConfirmActivity"
android:orientation="vertical"
android:weightSum="4">
<ImageView
android:id="#+id/imageView"
android:layout_width="203dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:src="#drawable/blank_pic"
/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hi"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="#+id/job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/job"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="#+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/age"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
/>
<TextView
android:id="#+id/description"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/description"
android:layout_weight="1"
/>
</LinearLayout>
Here is a screenshot indicating my problem. The fragment that Iwant to put into the tab is static in the background whereas the hello world string in the foreground is inside of the tabs so they change when I click on a new tab. I want to put my fragment inside of the first tab instead of it being in the background if that makes sense:

The problem is here:
ProfileFragment profileFragment = new ProfileFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_profile, profileFragment, "profileFragment");
transaction.commit();
This code creates an instance of ProfileFragment and adds it directly to the activity. Instead, you should create fragments that belong in a tab in the SectionsPagerAdapter and use it to manage which fragment is shown according to which tab is selected.

Hum, if i understood you want to use the view-pager to sweep the pages of each tab.
You don't need a "FrameLayout", because the Adapter of the ViewPager2 switch the fragment by giving the FragmentManager to the Adapter of the ViewPager2.
in the xml switch the ViewPager to ViewPager2.
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Create a new class that extends the FragmentStateAdapter, in this class you will be giving the number of the fragments that the ViewPager2 will be using to sweep between them.
public class FragmentAdapter_ViewPager extends FragmentStateAdapter {
public FragmentStateAdapter_ViewPager(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0://FIRST TAB
return new Fragment_Two();
case 1://SECOND TAB
return new Fragment_Three();
default:
return new Profile_Fragment();
}
return null;
}
#Override
public int getItemCount() {
return 3;
}
}
If you have more than one fragment to show in the tabs you can increment in the "createFragment()" method, just don't forget to say how many fragments will show in the method "getItemCount()".
Now in the SecoundActivity you can configure the new ViewPager2 with the Adapter and a new the LayoutMediator that synchronize them together.
//The Adapter of ViewPager2 that will switch the Fragments
viewPager2.setAdapter(new FragmentStateAdapter_ViewPager(getChildFragmentManager(), getLifecycle()));
//The LayoutMediator that will synchronize with the tabs
new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("TAB NAME"[position]);
}
}).attach();
Try to take a look int the GUIDE PAGE in:
Create swipe views with tabs using ViewPager2

Related

how to find button id of host activity in the fragment and send data to the host activity in the fragment

Edit: I changed my code as per the suggestion, but my app still crashes. I posted the error to the bottom of the question
I have been trying for 2 days to send an edittext data from a fragment to the main activity with a click of a button that is not in the fragment (it is in the host activity), and having trouble doing this even though I feel like the answer is probably simple!
There are answers on here that suggest an interface but I can not find any examples that don't use a button from in the fragment. When I attempt to find a button outside of the fragment and then send the data I get a runtime error.
My code
FormActivity.java, the part of the code that is supposed to receive the string is at the bottom in submitFormEntries
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.material.tabs.TabLayout;
public class FormActivity extends AppCompatActivity{
private static final String TAG = "PROCESS";
TabLayout tabLayout;
ViewPager viewPager;
oneFragment fragA = new oneFragment(); // this line can cause crashes
//or set to 0 and change it dynamically in the onPageSelected method
private int numFrags = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formactivity);
viewPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
getTabs();
//Add onPageChangeListener to get the position of the current tab and change the button text based on the position
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Button back = findViewById(R.id.backButton);
Button next = findViewById(R.id.nextButton);
Button mainReturn = findViewById(R.id.mainReturn);
Button submit = findViewById(R.id.submitButton);
PagerAdapter adapter = viewPager.getAdapter();
//numFrags = viewPager.getAdapter().getCoBunt() -1; - dynamically get new frags
if (position == 0) {
back.setVisibility(View.GONE);
next.setVisibility(View.VISIBLE);
mainReturn.setVisibility(View.VISIBLE);
}
else if (adapter != null && position == numFrags) {
back.setVisibility(View.VISIBLE);
next.setVisibility(View.GONE);
submit.setVisibility(View.VISIBLE);
}
else {
back.setVisibility(View.VISIBLE);
next.setVisibility(View.VISIBLE);
mainReturn.setVisibility(View.GONE);
submit.setVisibility(View.GONE);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
//Add fragments to viewPager using the object ViewPagerAdapter
public void getTabs(){
final ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
new Handler().post(new Runnable() {
#Override
public void run() {
viewPagerAdapter.addFragment(oneFragment.getInstance(),null); // `oneFragment.getInstance()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.addFragment(twoFragment.getInstance(),null); // `twoFragment.getInstance()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.addFragment(threeFragment.getInstance(),null); // `threeFragment.getInstance()` should be inside `FragmentPagerAdapter.getItem()`
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
});
}
//METHODS FOR THE BUTTON LISTENERS
public void goBack(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
}
public void goNext(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
public void submitFormEntries(View view) {
Intent intent = getIntent();
String message = intent.getStringExtra("Answer One");
Log.d(TAG, message);
}
public void returnToMainMenu(View view) {
Log.d(TAG, "returnToMainMenu: ");
}
}
My fragment code oneFragment.java:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class oneFragment extends Fragment{
private EditText answer_One;
public static oneFragment getInstance() {
oneFragment oneFragment = new oneFragment();
return oneFragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page_one, container, false);
final Button submit = (Button) getActivity().findViewById(R.id.submitButton);
answer_One = (EditText) view.findViewById(R.id.answerOne);
if(answer_One != null){
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(requireActivity().getBaseContext(),
FormActivity.class);
intent.putExtra("Answer One", answer_One.toString());
getActivity().startActivity(intent);
}
});
}
return view;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
ViewPagerAdaper.java
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private List<String> stringList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return stringList.get(position);
}
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment); // this line can cause crashes
stringList.add(title);
}
}
My error messages, edited to reflect answer
2021-01-07 19:08:07.767 8786-8786/net.larntech.tablayout E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.larntech.tablayout, PID: 8786
java.lang.IllegalStateException: Fragment oneFragment{9ca3c26} (7a20c5f2-8918-4de4-98a6-bed63353b415)} not attached to an activity.
at androidx.fragment.app.Fragment.requireActivity(Fragment.java:833)
at net.larntech.tablayout.oneFragment$1.onClick(oneFragment.java:37)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
EDIT: Here are the xmls
The main activity: activity_formctivity.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:orientation="vertical"
tools:context=".FormActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="#+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="goBack"
android:visibility="gone"/>
<Button
android:id="#+id/mainReturn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mainReturn"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="returnToMainMenu"
android:visibility="visible"/>
<Button
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="goNext"/>
<Button
android:id="#+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="submitFormEntries"
android:visibility="gone"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tabBackground="#drawable/tab_selector"
app:tabIndicatorHeight="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
fragment xml file page_one.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">
<TextView
android:id="#+id/titleOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/title_one"
android:textColor="#color/colorPrimaryDark"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/questionOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/questionOne"
android:textColor="#color/colorPrimaryDark"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/descriptionOne"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/descriptionOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/descriptionOne"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/answerOne"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/answerOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/answerHintOne"
android:inputType="textMultiLine"
android:maxLines="4"
android:minLines="4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
I need to do this with quite a few fragments by the way, so solutions like bundles and sharedprefs are not ideal. If the answer is to set up an interface, how do I go about doing this?
In your fragmentOne, you can't call getView() in onCreateView as the fragment view is not created yet; actually onCreateView() creates the fragment View and returns it.
So to solve this, you need to use the inflated view itself instead.
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page_one, container, false);
// answer_One = (EditText) getView().findViewById(R.id.answerOne); // returns NPE
answer_One = (EditText) view.findViewById(R.id.answerOne); // << Use this
...
UPDATE
You need to access activity's button in onResume of the fragment as below
#Override
public void onResume() {
super.onResume();
final Button submit = (Button) (FormActivity getActivity()).findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(requireActivity().getBaseContext(),
FormActivity.class);
intent.putExtra("Answer One", answer_One.toString());
getActivity().startActivity(intent);
}
});
}
And remove the button and its listener from onCreateView() method
The correct way to implement a regular FragmentPagerAdapter is:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new OneFragment();
if(position == 1) return new TwoFragment();
if(position == 2) return new ThreeFragment();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "ONE";
if(position == 1) return "TWO";
if(position == 2) return "THREE";
throw new IllegalStateException("Unexpected position " + position);
}
}
Then, to communicate from Fragment to Activity, the current Google-recommended approach is to use an Activity-scoped ViewModel that hosts a MutableLiveData.
public class MyViewModel extends ViewModel {
private final SavedStateHandle handle;
public MyViewModel(SavedStateHandle handle) {
this.handle = handle;
}
public final MutableLiveData<String> data = handle.getLiveData("data", "");
}
Then
public class MyActivity extends AppCompatActivity {
private MyViewModel myViewModel;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
}
}
And
public class MyFragment extends Fragment {
private MyViewModel myViewModel;
#Override
protected void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
}
}
Then you can mutate the LiveData and observe it for changes.

How to send fragment edittext data to activity without buttons in the fragment

I am making an application using fragments and viewpager that will send the users data to the main activity. The data will be collected from multiple fragments and be sent when the submit button (contained within the main activity) is pressed to the activity.
Example screenshot:
I am unsure how to get the fragment edittext data. I tried getting it in the onClick listener for the submit button with R.findViewById but it seems I'm missing an important step. I tried looking at videos/tutorials but I could only find applicable ones that got the data when a button was pressed in the fragment, or ones that did the reverse (fragment gets data from activity).
Here is my code:
formActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.material.tabs.TabLayout;
public class FormActivity extends AppCompatActivity {
private static final String TAG = "PROCESS";
TabLayout tabLayout;
ViewPager viewPager;
//or set to 0 and change it dynamically in the onPageSelected method
private int numFrags = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formactivity);
viewPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
getTabs();
//Add onPageChangeListener to get the position of the current tab and change the button text based on the position
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Button back = findViewById(R.id.backButton);
Button next = findViewById(R.id.nextButton);
Button mainReturn = findViewById(R.id.mainReturn);
Button submit = findViewById(R.id.submitButton);
PagerAdapter adapter = viewPager.getAdapter();
//numFrags = viewPager.getAdapter().getCoBunt() -1; - dynamically get new frags
if (position == 0) {
back.setVisibility(View.GONE);
next.setVisibility(View.VISIBLE);
mainReturn.setVisibility(View.VISIBLE);
}
else if (adapter != null && position == numFrags) {
back.setVisibility(View.VISIBLE);
next.setVisibility(View.GONE);
submit.setVisibility(View.VISIBLE);
}
else {
back.setVisibility(View.VISIBLE);
next.setVisibility(View.VISIBLE);
mainReturn.setVisibility(View.GONE);
submit.setVisibility(View.GONE);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
//Add fragments to viewPager using the object ViewPagerAdapter
public void getTabs(){
final ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
new Handler().post(new Runnable() {
#Override
public void run() {
viewPagerAdapter.addFragment(oneFragment.getInstance(),null); // this line can cause crashes
viewPagerAdapter.addFragment(twoFragment.getInstance(),null); // this line can cause crashes
viewPagerAdapter.addFragment(threeFragment.getInstance(),null); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
});
}
//METHODS FOR THE BUTTON LISTENERS
public void goBack(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
}
public void goNext(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
public void submitFormEntries(View view) {
Log.d(TAG, "returnToMainMenu: ");
}
public void returnToMainMenu(View view) {
Log.d(TAG, "returnToMainMenu: ");
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private List<String> stringList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return stringList.get(position);
}
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment); // this line can cause crashes
stringList.add(title);
}
}
oneFragment.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class oneFragment extends Fragment {
public static oneFragment getInstance(){
oneFragment oneFragment = new oneFragment();
return oneFragment;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page_one, container,false);
return view;
}
}
activity_formactivity.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:orientation="vertical"
tools:context=".FormActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="#+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="goBack"
android:visibility="gone"/>
<Button
android:id="#+id/mainReturn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mainReturn"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="returnToMainMenu"
android:visibility="visible"/>
<Button
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="goNext"/>
<Button
android:id="#+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="submitFormEntries"
android:visibility="gone"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tabBackground="#drawable/tab_selector"
app:tabIndicatorHeight="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
page_one.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">
<TextView
android:id="#+id/titleOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/title_one"
android:textColor="#color/colorPrimaryDark"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/questionOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/questionOne"
android:textColor="#color/colorPrimaryDark"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/descriptionOne"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/descriptionOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/descriptionOne"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/answerOne"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/answerOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/answerHintOne"
android:inputType="textMultiLine"
android:maxLines="4"
android:minLines="4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
I'm very new, so any alternative suggestions along with the answer would also be appreciated.
Use a Bundle. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
set values of first fragment in bundle.setArguments and onCreate() of second fragment get values using bundle.getInt()
in second fragment put same as bundle.setArguemnts with value of first fragment and second fragment so in 3rd fragmrnt you will get values of both fist and second fragment.
fragment 1:
Bundle bundle = new Bundle();
bundle.putString("FRAGEMNT1", "VALUE FRAGEMENT 1");
fragment.setArguments(bundle);
in fragment 2's onCrete()
Bundle bundle = this.getArguments();
if (bundle != null) {
String frag1Value = bundle.getString("FRAGEMNT1");
}
now put both value in fragment 2
Bundle bundle = new Bundle();
bundle.putString("FRAGEMNT1", "VALUE FRAGEMENT 1");
bundle.putString("FRAGEMNT2, "VALUE FRAGEMENT 2);
fragment.setArguments(bundle);
in fragment 3 onCrete()
Bundle bundle = this.getArguments();
if (bundle != null) {
String frag1Value = bundle.getString("FRAGEMNT1");
String frag2Value = bundle.getString("FRAGEMNT2");
}
now put both value in fragment 3
Bundle bundle = new Bundle();
bundle.putString("FRAGEMNT1", "VALUE FRAGEMENT 1");
bundle.putString("FRAGEMNT2, "VALUE FRAGEMENT 2);
bundle.putString("FRAGEMNT3, "VALUE FRAGEMENT 3");
fragment.setArguments(bundle);
now in activit's onCrete
Bundle bundle = this.getArguments();
if (bundle != null) {
String frag1Value=bundle.getString("FRAGEMNT1");
String frag2Value=bundle.getString("FRAGEMNT2");
String frag3Value=bundle.getString("FRAGEMNT3");
}
You can use SharedPreferences to store the data and retrieve the data when you need it.
Example :
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("key", "your answer");
editor.apply();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String answer= prefs.getString("key", "");
How about using ViewModel that is tied to FormActivity and save edit text value there
https://developer.android.com/topic/libraries/architecture/viewmodel?gclid=Cj0KCQiA3NX_BRDQARIsALA3fIJFaBMomx-KDhghEHZghVGwGaafvDwMpGzFxQFGm3M3_e0lv9Bzt1UaAoq7EALw_wcB&gclsrc=aw.ds
class FormViewModel : ViewModel() {
val answers: Map<String, String> = mutableMapOf()
}
fromFragment
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val viewmodel = ViewModelProviders.of(requireActivity()).get(FormViewModel::class.java)
viewModel.answer["SOME_KEY_HERE"] = s.toString()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
from activity you can access the value such
ViewModelProvider.of(this).get(FormViewModel::class.java).answer
Sorry, i write it in kotlin but you should be able to grab the idea
The correct way to implement a regular FragmentPagerAdapter is:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new RulesFragment();
if(position == 1) return new TreeFragment();
if(position == 2) return new PredictionFragment();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "TREE RULES";
if(position == 1) return "REGRESSION TREE";
if(position == 2) return "PREDICTION";
throw new IllegalStateException("Unexpected position " + position);
}
}
To get a reference to a Fragment created by a ViewPager, use the following findFragmentByTag scheme:
Fragment fragment = supportFragmentManager.findFragmentByTag("android:switcher:" + viewPager.getId() + ":" + fragmentPosition)
The correct way to communicate between multiple fragments is to use a ViewModel scoped to a shared scope (in this case, probably the Activity).
For that, refer to https://developer.android.com/codelabs/kotlin-android-training-view-model#0

must call setup() that takes a context and fragmentmanager - Rendering issue

I am trying to change my layout style using 'Design' option on android studio.
I get an error, saying that:
Exception raised during rendering: Must call setup() that takes a Context and FragmentManager (Details)
I can't understand what can cause this issue to occur, because when I run my app I can see the layout properly but can't edit it.
My class and layout are:
<?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:weightSum="1"
android:baselineAligned="false"
android:orientation="vertical"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<TextView
android:id="#+id/item_page_product_name"
android:layout_width="368dp"
android:layout_height="wrap_content"
android:text="#string/nike_show"
android:textSize="18sp"
android:background="#null"
tools:layout_editor_absoluteX="8dp"
android:padding="3dp"
android:paddingStart="8dp"
tools:ignore="MissingConstraints,RtlSymmetry"
tools:layout_editor_absoluteY="8dp" />
<TextView
android:text="#string/item_page_item_des"
android:layout_width="326dp"
android:layout_height="wrap_content"
android:id="#+id/item_page_product_des"
tools:ignore="MissingConstraints"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/item_page_product_name"
android:layout_marginStart="1dp"
app:layout_constraintLeft_toRightOf="#+id/item_page_item_id" />
<TextView
android:text="#string/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="8dp"
android:id="#+id/item_page_item_id"
tools:ignore="MissingConstraints"
android:layout_marginTop="8dp"
android:paddingStart="8dp"
app:layout_constraintTop_toBottomOf="#+id/item_page_product_name"
android:paddingRight="3dp"
android:paddingLeft="3dp" />
<android.support.v4.view.ViewPager
android:id="#+id/item_page_pager"
android:layout_width="368dp"
android:layout_height="213dp"
tools:layout_editor_absoluteX="8dp"
android:layout_marginTop="4dp"
app:layout_constraintTop_toBottomOf="#+id/item_page_product_des"
tools:ignore="MissingConstraints" />
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabsHostItem"
android:layout_width="368dp"
android:layout_height="325dp"
tools:layout_editor_absoluteX="8dp"
tools:ignore="MissingConstraints"
app:layout_constraintTop_toBottomOf="#+id/item_page_pager">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/tab"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="vertical"
tools:ignore="UselessParent">
<!--<TextView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text="#string/this_is_tab_1" />-->
</FrameLayout>
<!--<LinearLayout-->
<!--android:id="#+id/tab2"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:orientation="vertical">-->
<!--<TextView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text="#string/this_is_tab_2" />-->
<!--</LinearLayout>-->
<!--<LinearLayout-->
<!--android:id="#+id/tab3"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:orientation="vertical">-->
<!--<TextView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text="#string/this_is_tab_3" />-->
<!--</LinearLayout>-->
</FrameLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</android.support.constraint.ConstraintLayout>
Class:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.goldbergtom.cricket.adapters.ViewPagerAdapter;
import com.goldbergtom.cricket.fragments.DescriptionFragment;
import controller.ControllerDao;
public class ItemPageActivity extends AppCompatActivity {
private android.support.v4.app.FragmentTabHost mTabHost;
ViewPager viewPager;
PagerAdapter adapter;
int[] flag;
private LinearLayout mGallery;
private int[] mImgIds;
private LayoutInflater mInflater;
private HorizontalScrollView horizontalScrollView;
private ImageButton back;
private ImageButton www;
private ImageButton settings;
private TextView productMainTitle;
private TextView productId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_page);
mInflater = LayoutInflater.from(this);
productMainTitle = (TextView)findViewById(R.id.item_page_product_name);
productId = (TextView)findViewById(R.id.item_page_product_des);
// productMainTitle = (TextView)findViewById(R.id.item_page_product_name);
// productMainTitle = (TextView)findViewById(R.id.item_page_product_name);
String pMT = ControllerDao.currentSessionUser.getProducts()[0].get_title();
String pid = ControllerDao.currentSessionUser.getProducts()[0].getId();
productMainTitle.setText(pMT);
productId.setText(pid);
// TODO : yahav - remove the comments on the following code and look what it does
// android.support.v7.app.ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayShowTitleEnabled(false);
// actionBar.setDisplayShowHomeEnabled(false);
//
// View mCustomView = mInflater.inflate(R.layout.cricket_action_bar, null);
//
// actionBar.setCustomView(mCustomView);
// actionBar.setDisplayShowCustomEnabled(true);
//
// back = (ImageButton)findViewById(R.id.toolbar_back);
// back.setOnClickListener(backButtonFromItemActivity);
//
// www = (ImageButton)findViewById(R.id.toolbar_www);
// www.setOnClickListener(wwwButtonFromItemActivity);
//
// settings = (ImageButton)findViewById(R.id.toolbar_settings1);
// settings.setOnClickListener(settingsButtonFromItemActivity);
//
flag = new int[] { R.drawable.ic_1 , R.drawable.ic_2 , R.drawable.ic_3 };
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) findViewById(R.id.item_page_pager);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(ItemPageActivity.this, flag);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
mTabHost = (FragmentTabHost)findViewById(R.id.tabsHostItem);
// FragmentManager fm = getFragmentManager();
// android.app.FragmentTransaction ft = fm.beginTransaction();
// ft.commit();
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("DESCRIPTION",null),DescriptionFragment.class,null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("HISTORY",null),DescriptionFragment.class,null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("ALERTS",null),DescriptionFragment.class,null);
//Tab 1
// TabHost.TabSpec spec = host.newTabSpec("DESCRIPTION");
// spec.setContent(R.id.tab1);
// spec.setIndicator("Tab One");
// host.addTab(spec);
//
// //Tab 2
// spec = host.newTabSpec("HISTORY");
// //spec.setContent(R.layout.fragment_description);
// spec.setContent(R.id.tab2);
// spec.setIndicator("Tab Two");
// host.addTab(spec);
//
// //Tab 3
// spec = host.newTabSpec("ALERTS");
// spec.setContent(R.id.tab3);
// spec.setIndicator("Tab Three");
// host.addTab(spec);
// CricketDao.GetDataTask gdt = new CricketDao.GetDataTask();
// String s = null;
// JSONObject jObject = null, subject = null;
// JSONArray arr = null;
// String title=null;
// try {
// // TODO : Place resonse as USER object to const
// s = gdt.execute("https://cricketweb.herokuapp.com/checkLogin").get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
}
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_item_activity, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()){
// when clicking on the URL icon, it will open the product page through browser.
case R.id.action_web:
startActivity(new Intent(this, LoginActivity.class));
return true;
// when clicking on delete item it will delete the item from wish list and go back to wish list page.
case R.id.delete_item:
startActivity(new Intent(this, WishListActivity.class));
return true;
// when clicking on purchased item, it will stay on this activity and change on DB from 0 to 1 (help us with adaptation)
case R.id.purchased_item:
startActivity(new Intent(this, LoginActivity.class));
return true;
// when clicking on settings, it will give the user another view of settings option.
case R.id.action_settings:
startActivity(new Intent(this, LoginActivity.class));
return true;
// when clicking on back icon it will go back to previous screen.
case R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
View.OnClickListener backButtonFromItemActivity = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "backButtonFromItemActivity", Toast.LENGTH_SHORT).show();
}
};
View.OnClickListener wwwButtonFromItemActivity = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "wwwButtonFromItemActivity", Toast.LENGTH_SHORT).show();
}
};
View.OnClickListener settingsButtonFromItemActivity = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "settingsButtonFromItemActivity", Toast.LENGTH_SHORT).show();
}
};
private void initData()
{
mImgIds = new int[] { R.drawable.ic_1, R.drawable.ic_2, R.drawable.ic_3,R.drawable.ic_4
};
}
public void toggle_contents(View v){
new DescriptionFragment().toggle_contents(v);
}
public void toggle_contents2(View view) {
new DescriptionFragment().toggle_contents2(view);
}
}
This rendering error occurs because the android studio layout renderer still uses the deprecated setup() method. there's actually an open issue about this here
If setup properly like you have it will work as intended when you run the app. the only downside is that you will not get to see the rendered view on the editor until the android team posts a fix for this.

Implementing Swipe functionality on portion of screen while using bottom navigation?

I am developing my first Android application as part of a college project. I am relatively new to java. My application consists of a bottom navigation, which contains 4 separate pages. Within these pages I have a head section, containing a title, contact button and logout button.
Underneath the head section I wish to have a midsection which will in itself contain 3 swipe panels containing information. Essentially there should be 3 panels for each page, with there being 4 pages (So 4 sets of 3 swipe panels).
This is where I'm having difficulty.. I'm unsure of how to nest the fragments so that only that midsection will be swipe-able. Here is a screenshot of what I have so far:
Screenshot of app
Here is my Code for my MainActivity.java class:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
frag = MenuFragment.newInstance(getString(R.string.text_home),
getString(R.string.test_home));
break;
case R.id.menu_notifications:
//Call to a function that does the stuff here
frag = MenuFragment.newInstance(getString(R.string.text_notifications),
getString(R.string.test_notifications));
break;
case R.id.menu_search:
frag = MenuFragment.newInstance(getString(R.string.text_search),
getString(R.string.test_search));
break;
case R.id.menu_followed:
frag = MenuFragment.newInstance(getString(R.string.text_follow),
getString(R.string.test_follow));
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here is the acitivity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.socialivemusic.socialivetestproject.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ff292929">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="0.06"
android:background="#ff000000"
android:textAlignment="center"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
And here is my MenuFragment.java class:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private static final String ARG_TESTSTRING = "arg_testString";
private String mText;
private String mTest;
private View mContent;
private TextView mTextView;
private TextView mTestView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text, String testString) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putString(ARG_TESTSTRING, testString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve text and color from bundle or savedInstanceState
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
mTest = args.getString(ARG_TESTSTRING);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
mTest = savedInstanceState.getString(ARG_TESTSTRING);
}
// initialize views
mContent = view.findViewById(R.id.fragment_content);
mTextView = (TextView) view.findViewById(R.id.text);
mTestView = (TextView) view.findViewById(R.id.test);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text and background color
mTextView.setText(mText);
mTestView.setText(mTest);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
outState.putString(ARG_TESTSTRING, mTest);
super.onSaveInstanceState(outState);
}
}
Here is the fragments_menu.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.socialivemusic.socialivetestproject.MenuFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="150dp"
android:layout_marginTop="15dp"
android:background="#ff434343"
android:weightSum="1">
<Button
android:text="CONTACT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/contactButton"
android:layout_weight="0.33"
android:background="#drawable/round_button"
android:textSize="20sp"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#969696"
android:textSize="40sp"
android:textStyle="bold"
android:layout_weight="0.355"
/>
<Button
android:text="LOGOUT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/logoutbutton"
android:layout_weight="0.33"
android:background="#drawable/logout_button"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="185dp"
android:background="#ff434343">
<TextView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
The second LinearLayout in the above file is the one which should be the swipe-panel. The only other files on the project are xml files dealing with layout of the bottom navigation bar itself, so not relevant to the trouble I'm having.
Does anyone have any recommendations on how to approach this? A helping hand on how to start this part of the project would be amazing! Thanks in advance!

saving & reloading edittext value when switching between fragments

java & Two.java)
into each fragments there's editext:
One : editText_One
Two : editText_Two
How to save and resotre editText_One (and editText_Two), when i switch between fragments?
I've tried several things after reading tutos, but nothing working well ;(
One.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="one" />
<EditText
android:layout_width="237dp"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/editText_One"
android:text="blabla"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Two.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TWO" />
<EditText
android:layout_width="237dp"
android:layout_height="wrap_content"
android:inputT`enter code here`ype="date"
android:ems="10"
android:id="#+id/editText_Two"
android:layout_gravity="center_horizontal" />
One.java :
/**
*
*/
package com.example.navigationsubmenu;
/**
* #author info-medios
*
*/
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class One extends Fragment {
// public static final String EXTRA_URL_nommatiere = "url";
EditText editText_one;
// String valeur;
private final String PERSISTENT_VARIABLE_BUNDLE_KEY = "persistentVariable";
public One() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle bundle = new Bundle();
/* Bundle bundle = getActivity().getIntent().getExtras();
Bundle mySavedInstanceState = getArguments();
if (bundle!= null) {// to avoid the NullPointerException
// editText_one.setText("premiere");
String persistentVariable = mySavedInstanceState.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
editText_one.setText(persistentVariable);
}*/
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
String persistentVariable = extras.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
editText_one.setText(persistentVariable);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.one, container, false);
//Instancier vos composants graphique ici (faƮtes vos findViewById)
editText_one = (EditText) view.findViewById(R.id.editText_One); //getview marche aussi
/* Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
valeur = extras.getString(EXTRA_URL_nommatiere); //Affiche le nom matiere
}
else
{
}
editText_one.setText(valeur );*/
return view;
}
#Override
public void onPause() {
super.onPause();
String persistentVariable = editText_one.getText().toString();
Intent intent = new Intent(getActivity(), One.class);
intent.putExtra(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
//startActivity(intent);
getArguments().putString(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
}
/* #Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle extras = getActivity().getIntent().getExtras();
if (savedInstanceState != null) {
// Restore last state for checked position.
valeur = extras.getString(EXTRA_URL_nommatiere);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("TEXT", valeur);
}*/
/* #Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.v(TAG, "Inside of onRestoreInstanceState");
valeur = extras.getString(EXTRA_URL_nommatiere);
}*/
}
Can someone can help me please,
many thnaks
First you need to attach the fragments to activity then you can simply define two strings String one ,String two in the activity containing the fragments and assign the value of each editText to diffrent one
i.e
String one=editTextOne.getText.toString();
String two=editTextTwo.getText.toString();
When you have to switch between either activities or fragments, you can use Shared Preferences to store a small amount of datas and retrieve them.
Shared Prefs are small sets of key/value pairs.
Write
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
You can write and read any primitive data types such as Strings using put[Type] and get[Type] methods.
Source codes above come from the official android developer training and belongs to Android.
"is there a way with saveInstanceState ?"
I think this bundle is usefull when one activity is destroyed and created by Screen rotation or resumed after a call, but not when switching between activities and fragments.
But you can try it. I know that views like EditText with id have a built-in saveInstanceState so you do not have to handle it manually.
To switch between fragments you can use activity class scoped properties. You will need to add interfaces to your fragments to allow them to communicate with the activity.
EXAMPLE
The following example shows how to switch between fragments and keep EditText values.
The MainActivity contains a FrameLayout and two buttons. The fragment transaction is done on button click events.
Fragments include an interface to communicate with the activity. Each time the EditText value is changed, the activity's property is updated.
The activity communicates with the fragment to set EditText value right after the transaction.
First of all, here are xml layouts files for the MainActivity, the FragmentA and the FragmentB classes :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="morbak.stackoverflow.fragmentcommunication.MainActivity">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:orientation="horizontal"
android:weightSum="100">
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:text="Fragment A" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:text="Fragment B" />
</LinearLayout>
</LinearLayout>
activity_main.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">
<EditText
android:id="#+id/etOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Fragment A content"/>
</LinearLayout>
fragment_a.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">
<EditText
android:id="#+id/etTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Fragment B content"/>
</LinearLayout>
fragment_b.xml
Then, here are Fragments A and B classes. Source code is self explanatory.
package morbak.stackoverflow.fragmentcommunication;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class FragmentA extends Fragment {
//Views
EditText etOne;
//Fields
String value;
//Listeners
OnFragmentASelectedListener mCallback;
//Context
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate views and layouts
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
etOne = (EditText) rootView.findViewById(R.id.etOne);
//Events
etOne.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Execute the interface's abstract method
mCallback.onFragmentASelected(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
etOne.setText(value);
return rootView;
}
//Set the fragment's field value
public void setEditText(String newValue) {
value = newValue;
}
//Interface
public interface OnFragmentASelectedListener {
public void onFragmentASelected(String value);
}
//Throws an exception if the activity implements FragmentA.OnFragmentASelectedListener, but not the abstract method
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFragmentASelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentASelectedListener");
}
}
}
FragmentA.java
The same work should be done with FragmentB, but you obviously have to search and replace FragmentA to FragmentB and etOne to etTwo.
Finally, here is the MainActivity who handles fragment transactions and uses fragments' listeners :
package morbak.stackoverflow.fragmentcommunication;
import android.content.Context;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements FragmentA.OnFragmentASelectedListener, FragmentB.OnFragmentBSelectedListener {
Button button1;
Button button2;
FragmentTransaction transaction;
FragmentA fragmentA;
FragmentB fragmentB;
String editTextOne;
String editTextTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
editTextOne = "";
editTextTwo = "";
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
transaction = getSupportFragmentManager().beginTransaction();
fragmentA = new FragmentA();
transaction.replace(R.id.fragment_container, fragmentA);
transaction.addToBackStack(null);
transaction.commit();
fragmentA.setEditText(editTextOne);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
transaction = getSupportFragmentManager().beginTransaction();
fragmentB = new FragmentB();
transaction.replace(R.id.fragment_container, fragmentB);
transaction.addToBackStack(null);
transaction.commit();
fragmentB.setEditText(editTextTwo);
}
});
}
public void onFragmentASelected(String value) {
editTextOne = value;
}
public void onFragmentBSelected(String value) {
editTextTwo = value;
}
}
MainActivity.java

Categories

Resources