I am trying to replace one fragment with another on button click listener in Adapter Class. Compiler is going to the onClickListener but the fragment is not replacing.
#OnClick(R.id.ib_view)
public void gotoTranscationDetailsFragment() {
Toast.makeText(mParent, "Hi", Toast.LENGTH_SHORT).show();
Fragment viewSuspendedTransactionFragment = new ViewSuspendedTransactionFragment();
FragmentManager manager = mParent.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_suspend_transaction, viewSuspendedTransactionFragment);
transaction.commit();
}
FULL CODE
public class SuspendedTransactionListAdapter extends RecyclerView.Adapter<SuspendedTransactionListAdapter.SuspendedTransactionListHolder> {
private SuspendTransactionActivity mParent;
private List<SuspendTransactionFragment.SampleDataSuspendTransactionActivity> sampleList;
private Fragment fragment;
public SuspendedTransactionListAdapter(SuspendTransactionActivity mParent, List<SuspendTransactionFragment.SampleDataSuspendTransactionActivity> sampleList, Fragment fragment) {
this.mParent = mParent;
this.sampleList = sampleList;
this.fragment = fragment;
}
#Override
public SuspendedTransactionListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_suspended_transaction_list, parent, false);
return new SuspendedTransactionListHolder(itemView);
}
#Override
public void onBindViewHolder(SuspendedTransactionListHolder holder, int position) {
SuspendTransactionFragment.SampleDataSuspendTransactionActivity sampleDataSuspendTransactionActivity = sampleList.get(position);
holder.mTransactionNoTextView.setText(sampleDataSuspendTransactionActivity.getTransactionNo());
}
#Override
public int getItemCount() {
return sampleList.size();
}
class SuspendedTransactionListHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ib_view)
ImageButton mViewImageButton;
public SuspendedTransactionListHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
#OnClick(R.id.ib_view)
public void gotoTranscationDetailsFragment() {
Toast.makeText(mParent, "Hi", Toast.LENGTH_SHORT).show();
Fragment viewSuspendedTransactionFragment = new ViewSuspendedTransactionFragment();
FragmentManager manager = mParent.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_suspend_transaction, viewSuspendedTransactionFragment);
transaction.commit();
}
}
XML - Activity
<?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=".transaction.activities.SuspendTransactionActivity">
<fragment
android:id="#+id/fragment_suspend_transaction"
class="com.sahasram.siripos.fragments.SuspendTransactionFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/actionbar"
tools:layout="#layout/fragment_suspend_transaction" />
</RelativeLayout>
If you define a Fragment in your xml using the tag <fragment> then it is a constant part of your View hierarchy and you can't remove/replace it. If you want to replace Fragment you should define a layout that is replaceable (serves as a container for your Fragment). So, your Activity layout could be as follows:
<?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=".transaction.activities.SuspendTransactionActivity">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/actionbar" />
</RelativeLayout>
And then you can replace it afterwards as:
#OnClick(R.id.ib_view)
public void gotoTranscationDetailsFragment() {
Toast.makeText(mParent, "Hi", Toast.LENGTH_SHORT).show();
Fragment viewSuspendedTransactionFragment = new ViewSuspendedTransactionFragment();
FragmentManager manager = mParent.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, viewSuspendedTransactionFragment);
transaction.commit();
}
For more information please look here
Related
When I press the button in the InputFragmentNew fragment, I want the newRegistrationFragment to open. But when I try to open it, I have the following problem. How do I switch from one fragment to another?
First Class
public class GirisFragmentNew extends Fragment implements View.OnClickListener{
btnKAyit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new yeniKayıtFragment());
fragmentTransaction.commit();
}
});
}
Second Fragment
public class yeniKayıtFragment extends Fragment {
private yeniKayıtModel yeniKayıtModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
yeniKayıtModel =
ViewModelProviders.of(this).get(yeniKayıtModel.class);
View root = inflater.inflate(R.layout.fragment_yenikayit, container, false);
Window window=getActivity().getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setNavigationBarColor(getResources().getColor(R.color.colorPrimary));}
return root;
}
Second Class Xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="...yeniKayıtFragment">
<FrameLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/fragment_container"
/>
<WebView
android:id="#+id/webviewYeniKayıt"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
In your MainActivity create this public variable
public static FragmentManager manager;
then inside the onCreate method
manager = getSupportFragmentManager();
then in your GirisFragmentNew fragment
btnKAyit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yeniKayıtFragment fragment = new yeniKayıtFragment();
MainActivity.manager.beginTransaction().replace(R.id.fragment_container,fragment,yenTAG).commit();
}
});
In case of Fragment you have to use getChildFragmentManager instead of getFragmentManager. Don't use static variable which you have tried. Check below:
btnKAyit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new yeniKayıtFragment());
fragmentTransaction.commit();
}
});
im developing an android app which has a bottomnavigation that opens 3 different fragments without a viewpager. One fragment has a viewpager inside it which opens 2 fragments. these 2 fragments are the same fragment and each has a recyclerview inside it. my problem is that when I run the app everything except the viewpager runs as intended. I tried putting the fragment inside the viewpager instead of it and the fragment works. I even tried putting the viewpager in a empty activity which worked as well.
This is my MainActivity which holds the BottomNavigation and its functionality:
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private androidx.appcompat.widget.Toolbar toolbar;
private BottomNavigationView navView;
private Fragment fragment1 = new HomeFragment();
private Fragment fragment2 = new SearchFragment();
private Fragment fragment3 = new SettingsFragment();
private FragmentManager fm = getSupportFragmentManager();
private Fragment active = fragment1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.action_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
fm.beginTransaction().add(R.id.main_container, fragment3, "settings").hide(fragment3).commit();
fm.beginTransaction().add(R.id.main_container, fragment2, "search").hide(fragment2).commit();
fm.beginTransaction().add(R.id.main_container, fragment1, "home").commit();
navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fm.beginTransaction().hide(active).show(fragment1).addToBackStack("home").commit();
active = fragment1;
toolbar.setTitle("Home");
return true;
case R.id.navigation_search:
fm.beginTransaction().hide(active).show(fragment2).addToBackStack("search").commit();
active = fragment2;
toolbar.setTitle("Search");
return true;
case R.id.navigation_settings:
fm.beginTransaction().hide(active)
.show(fragment3).addToBackStack("settings").commit();
active = fragment3;
toolbar.setTitle("Settings");
return true;
}
return false;
}
public void setCurrentPage(Fragment fragment, int position) {
if(fm.findFragmentByTag("playlist"+position) != null){
fm.beginTransaction().remove(fragment).hide(active).add(R.id.main_container, fragment, "playlist"+position).addToBackStack(null).commit();
active = fragment;
} else {
fm.beginTransaction().hide(active).add(R.id.main_container, fragment, "playlist"+position).addToBackStack(null).commit();
active = fragment;
}
}
}
This is the MainActivityLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
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"
tools:context=".MainActivity">
<include
layout="#layout/action_bar"
android:id="#+id/action_bar"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:layout_marginBottom="70dp"
android:id="#+id/main_container_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/main_container"/>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_nav_menu"
app:itemTextColor="#color/bottom_nav_color"
app:itemIconTint="#color/bottom_nav_color"
android:elevation="20dp"/>
</RelativeLayout>
This is my Fragment that implements the ViewPager:
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
PlaylistsPagerAdapter playlistsPagerAdapter = new PlaylistsPagerAdapter(getChildFragmentManager());
playlistsPagerAdapter.addFragment(new PlaylistsFragment(),"private");
playlistsPagerAdapter.addFragment(new PlaylistsFragment(),"public");
ViewPager viewPager = view.findViewById(R.id.pager_home);
viewPager.setAdapter(playlistsPagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tab_layout_home);
tabLayout.setupWithViewPager(viewPager);
setHasOptionsMenu(false);
}
public class PlaylistsPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> mFragmentList = new ArrayList<>();
ArrayList<String> mFragmentListTitle = new ArrayList<>();
public void addFragment(Fragment playlistsFragment, String title) {
mFragmentListTitle.add(title);
mFragmentList.add(playlistsFragment);
}
public PlaylistsPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int i) {
return mFragmentList.get(i);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentListTitle.get(position);
}
}
}
This is the HomeFragmentLayout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager_home"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout_home"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.viewpager.widget.ViewPager>
This is the PlaylistsFragment:
public class PlaylistsFragment extends Fragment {
private static final String TAG = "PlaylistsFragment";
private ArrayList<String> mPlaylistName = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_playlists, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initNameBitmap(view);
}
private void initNameBitmap(View view){
mPlaylistName.add("Playlist1");
mPlaylistName.add("Playlist2");
mPlaylistName.add("Playlist3");
mPlaylistName.add("Playlist4");
initRecyclerView(view);
}
private void initRecyclerView(View view){
RecyclerView recyclerView = view.findViewById(R.id.recycler_view_playlists);
RecyclerViewAdapterPlaylists recyclerViewAdapterPlaylists = new RecyclerViewAdapterPlaylists(mPlaylistName, view.getContext(),this);
recyclerView.setAdapter(recyclerViewAdapterPlaylists);
recyclerView.setLayoutManager(new LinearLayoutManager(getView().getContext()));
}
}
This is the PlaylistsFragments Layout:
<?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">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view_playlists"
android:layout_margin="10dp" />
</LinearLayout>
The weird thing is that it worked already. I tried around with onBackPressed and when i implemented this and pressed another View on the BottomNavigation than the back button on the phone and than the Home button it showed as intened:
fm.beginTransaction().hide(active).show(fragmentsHistory.get(fragmentsHistory.size()-1));
active = fragmentsHistory.get(fragmentsHistory.size()-1)
fragmentsHistory.remove(fragmentsHistory.size()-1);
What am I doing wrong?
Appreciate the help!
i think the problem is in your layout
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".ui.plans.PlansFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#DBD8D8" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
your HomeFragmentLayout should be similar to this
I have a image in the main activity and when this image is clicked i want to show the fragmentA that has a list view.
When a item of this listView is clicked i want to replace the fragmentA by the fragmentB that has a textview, and I want to show in this textview the text associated to the clicked list item.
So in main activity I have this:
public class MainActivity extends AppCompatActivity implements Listener{
private ImageView img;
private String text;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
img = (ImageView) findViewById(R.id.imageView);
}
public void AddFragmentA(View view) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentA, new FragmentA(), "fragA");
transaction.commit();
}
public void AddFragmentB() {
FragmentB fragment = new FragmentB();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
transaction.commit();
}
#Override
public void addText(String text) {
this.text = text;
Toast.makeText(this, "Text received in Activity:" +text, Toast.LENGTH_SHORT).show();
sendDataToFragmentB();
}
public void sendDataToFragmentB(){
FragmentB fragmentB = (FragmentB) fragmentManager.findFragmentByTag("fragB");
fragmentB.addText(text);
}
}
Note: The toast in addText() appears with the correct text at this point, so the text of the list view is received in Activity with success.
Question: Now how to replace fragmentA with fragmentB and show the textview with the received text in the activity instead of showing the listview of the fragmentA?
Below is all the complete example.
FragmentA class:
public class FragmentA extends Fragment{
private ListView listItems;
private String[] items = {
"item1",
"item2",
"item3",
"item4"
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listItems = (ListView) getView().findViewById(R.id.listviewInFragment);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, items);
listItems.setAdapter(adapter);
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int positionCode = i;
String clickedValue = (String) adapterView.getItemAtPosition(i);
Listener listener = (Listener) getActivity();
listener.addText(clickedValue);
}
});
}
}
FramentB:
public class FragmentB extends Fragment {
private TextView tv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
tv = (TextView) getView().findViewById(R.id.textView);
return view;
}
public void addText(String text) {
String result = text;
tv.setText(result);
}
}
main activity xml:
<?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">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/image"
android:onClick="AddFragmentA"
tools:layout_editor_absoluteX="0dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp" />
<FrameLayout
android:id="#+id/containerFragmentA"
android:layout_width="0dp"
android:layout_height="300dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"
tools:layout_editor_absoluteY="1dp">
</FrameLayout>
<FrameLayout
android:id="#+id/containerFragmentB"
android:layout_width="0dp"
android:layout_height="300dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"
tools:layout_editor_absoluteY="1dp">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
fragment a xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0ff">
<ListView
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="16dp"
android:id="#+id/listviewInFragment"/>
</android.support.constraint.ConstraintLayout>
fragment b xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
/>
</android.support.constraint.ConstraintLayout>
This is how you will achieve the required task.
make chnages to your class accordingly below.
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentA.ClickListener{
private Button button;
public static String EXTRA_STRING = "extraString";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddFragment(FragmentA.getInstance());
}
});
}
public void AddFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.containerFragmentA, fragment).commit();
}
#Override
public void onClick(String data) {
AddFragment(FragmentB.getInstance(data));
}
}
activity_main.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/containerFragmentA"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="1dp"/>
<Button
android:id="#+id/button"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_margin="8dp"
android:layout_alignParentBottom="true"
android:text="Add Fragment B"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
FragmentA.java
public class FragmentA extends Fragment {
private ListView listItems;
private String[] items = {"item1", "item2", "item3", "item4"};
private ClickListener clickListener;
public static FragmentA getInstance() {
return new FragmentA();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
clickListener = (ClickListener)context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listItems = (ListView) getView().findViewById(R.id.listviewInFragment);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, items);
listItems.setAdapter(adapter);
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String clickedValue = items[i];
clickListener.onClick(clickedValue);
}
});
}
public interface ClickListener{
void onClick(String data);
}
}
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="16dp"
android:id="#+id/listviewInFragment"/>
</android.support.constraint.ConstraintLayout>
FragmentB.java
public class FragmentB extends Fragment {
private TextView tv;
private String data;
public static FragmentB getInstance(String data){
Bundle bundle = new Bundle();
bundle.putString(MainActivity.EXTRA_STRING,data);
FragmentB fragmentB = new FragmentB();
fragmentB.setArguments(bundle);
return fragmentB;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
tv = view.findViewById(R.id.textView);
data = getArguments().getString(MainActivity.EXTRA_STRING);
addText(data);
return view;
}
public void addText(String text) {
String result = text;
tv.setText(result);
}
}
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:gravity="center"
android:textSize="24dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.PopupMenu.Header"
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
you are placing fragment A in below function instead of fragment B
public void AddFragmentB() {
FragmentB fragment = new FragmentB();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
transaction.commit();
}
it should be
public void AddFragmentB() {
FragmentB fragment = new FragmentB();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.containerFragmentB, new FragmentB(), "fragB");
transaction.commit();
}
if you want to replace a fragment with another just use the same container
don't create separate (R.id.containerFragmentB, R.id.containerFragmentA) container.
You need to change your
public void AddFragmentA(View view) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentA, new FragmentA(), "fragA");
transaction.commit();
}
public void AddFragmentB() {
FragmentB fragment = new FragmentB();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
transaction.commit();
}
to
public void AddFragmentA(View view) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.container, fragmentA , "fragA");
transaction.commit();
}
public void AddFragmentB() {
FragmentB fragment = new FragmentB();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.container, fragment, "fragB");
transaction.commit();
}
and activity_main.xml should be
<?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">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/image"
android:onClick="AddFragmentList"
tools:layout_editor_absoluteX="0dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp" />
<FrameLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="300dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"
tools:layout_editor_absoluteY="1dp">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
EDIT
listItems.setAdapter(adapter);
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int positionCode = i;
String clickedValue = (String) adapterView.getItemAtPosition(i);
Listener listener = (Listener) getActivity();
listener.addText(clickedValue);
}
});
Listener
public interface IScanner {
void addText(String Text);
}
MainActivity
public class MainActivity extends AppCompatActivity implements Listener{
private ImageView img;
private String text;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
img = (ImageView) findViewById(R.id.imageView);
}
public void AddFragmentA(View view) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentA, new FragmentA(), "fragA");
transaction.commit();
}
#Override
public void addText(String text) {
this.text = text;
Toast.makeText(this, "Text received in Activity:" +text, Toast.LENGTH_SHORT).show();
sendDataToFragmentB(text);
}
public void sendDataToFragmentB(String clickedValue){
Bundle b = new Bundle();
b.putString("clickedValue", clickedValue);
FragmentB fragment = new FragmentB();
fragment.setArguments(b);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
transaction.commit();
}
}
FragmentB
public class FragmentB extends Fragment {
private TextView tv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
tv = (TextView) getView().findViewById(R.id.textView);
return view;
}
Bundle bundle = this.getArguments();
if (bundle != null) {
String text = bundle.getString("clickedValue", "");
}
}
This will solve your problem
I want to create a fragment for each element. I turn this back to the size of my list in RecyclerView, and I have defined a frame layout in my RecyclerView layout. How do I bind a fragment to the framelayout for each element?
Sample Adapter =
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private Context context;
private HashMap<Integer, Order> tester;
private TotalFragment fragment;
private FragmentManager fm;
public Adapter(Context context , HashMap<Integer, Order> tester, FragmentManager fm) {
this.context = context;
this.tester = tester;
this.fm = fm;
}
#Override
public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(Adapter.ViewHolder holder, int position) {
fragment = new TotalFragment();
int id =holder.totalFragment.generateViewId();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(id,fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public int getItemCount() {
return tester.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
FrameLayout totalFragment;
ViewHolder(View itemView) {
super(itemView);
totalFragment = (FrameLayout) itemView.findViewById(R.id.deneme);
}
}
}
Adapter Layout =
<?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">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/deneme"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
</LinearLayout>
I think you could use onCreateView() inside the fragment and inflate your framelayout.
The following is layout
test.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">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Click"
android:id="#+id/button"
/>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
test_detail.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hello"
android:id="#+id/textView" android:layout_gravity="center_horizontal"/>
</LinearLayout>
common_view_pager_layout
<?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.support.v4.view.ViewPager
android:id="#+id/MainViewerPage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.PagerTabStrip
android:id="#+id/TitlePageTabStrip"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v4.view.ViewPager>
</LinearLayout>
The following is my Activity code
public class TestFragmentActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, new HomeFragment()).commit();
}
});
}
public class HomeFragment extends Fragment {
private PagerAdapter _adapter;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.common_view_pager_layout, container, false);
this._adapter = new PagerAdapter(TestFragmentActivity.this);
this._adapter.add(new DetailFragment());
ViewPager pager = (ViewPager) view.findViewById(R.id.MainViewerPage);
pager.setAdapter(this._adapter);
return view;
}
}
public class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test_detail, container, false);
return rootView;
}
}
public class PagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> _fragments;
public PagerAdapter(FragmentActivity activity) {
super(activity.getSupportFragmentManager());
this._fragments = new ArrayList<Fragment>();
}
public void add(Fragment fragment) {
this._fragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return this._fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return "Test";
}
#Override
public int getCount() {
return 1;
}
}
}
When I click a button the fragment in ViewPager was display
But when I click the button again the fragment disappear
Please help me.
try using this:
in the constructor of your adapter change this :
public class MyPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> _fragments;
public MyPagerAdapter(FragmentManager activity) {
super(activity);
this._fragments = new ArrayList<Fragment>();
}
public void add(Fragment fragment) {
this._fragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return this._fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return "Test";
}
#Override
public int getCount() {
return 1;
}
}
and when you want to create the adapter send getChildFragmentManager() to its constructor
public class HomeFragment extends Fragment {
private MyPagerAdapter _adapter;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.common_view_pager_layout, container, false);
ViewPager pager = (ViewPager) view.findViewById(R.id.MainViewerPage);
this._adapter = new MyPagerAdapter(getChildFragmentManager());
this._adapter.add(new DetailFragment());
pager.setAdapter(this._adapter);
return view;
}
}
I test it and it works, any problem comment it.
Good Luck!
In your Fragment class, in the onCreate() method, you have to call setRetainInstance(true) like this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
This tells the FragmentManager to keep your fragments on reloads.
In addition, check your manifest file doesn't have any
android:screenOrientation
config changes where you are basically saying you will handle reloads due to config changes yourself.
In PagerFragment 's onResume() add this:
#Override
public void onResume() {
super.onResume();
for (Fragment fragment : getFragmentManager().getFragments()) {
if (fragment instanceof Tab1Fragment || fragment instanceof Tab2Fragment) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(fragment);
ft.attach(fragment);
ft.commit();
}
}
}
Try to add this lines in your code:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
and Add the below lines
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
... anything you may need to do to handle pager state ...
adapter.notifyDataSetChanged(); //this line will force all pages to be loaded fresh when changing between fragments
}
Under
pager.setAdapter(adapter);
Hope this may help you!
Ensure you pass the adapter instance the child fragment manager, not the fragment manager.
Like this:
this._adapter = new PagerAdapter(getChildFragmentManager());