Calling a fragment a second time makes it invisible - java

So it is exactly as the title suggests. I've created an app of which I will put the code beneath here, and when I call a fragment from the automaticly generated Home fragment which generates when you choose the template Navigation Drawer Activity, it pops up fine, and when I swipe back it dissapears again.
However, then when I press the button to call a fragment the second time, it just shows an empty screen.
MainActivity.java:
package eu.sleepy.emptyfragmentbug2;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.widget.FrameLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
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();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
System.out.println("popping backstack");
if (fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("findThisFragment")) {
View linearLayout = findViewById(R.id.homefrag);
linearLayout.setVisibility(View.VISIBLE);
FrameLayout frameLayout = findViewById(R.id.blankfrag);
frameLayout.setVisibility(View.GONE);
}
} else {
System.out.println("nothing on backstack, calling super");
super.onBackPressed();
}
}
}
HomeFragment.java
package eu.sleepy.emptyfragmentbug2.ui.home;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import eu.sleepy.emptyfragmentbug2.BlankFragment;
import eu.sleepy.emptyfragmentbug2.R;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
BlankFragment nextFrag = new BlankFragment();
nextFrag.color = Color.LTGRAY; // This value is always different when the button is pressed, so calling the same fragment wouldn't work.
getParentFragment().getFragmentManager().beginTransaction()
.replace(((ViewGroup)getView().getParent()).getId(), nextFrag, "findThisFragment")
.addToBackStack("findThisFragment")
.commit();
View linearLayout = getActivity().findViewById(R.id.homefrag);
linearLayout.setVisibility(View.GONE);
}
};
Button button = root.findViewById(R.id.button);
button.setOnClickListener(onClickListener);
Button button2 = root.findViewById(R.id.button2);
button2.setOnClickListener(onClickListener);
return root;
}
}
It is commented in the code, but I'll say it here again nextFrag.color = Color.LTGRAY; is almost never the exact same color and thus is different every time, so defining the fragment once and calling the same fragment again when one button is called is not a viable option.
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/homefrag"
tools:context=".ui.home.HomeFragment">
<TextView
android:id="#+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="63dp"
android:layout_marginTop="155dp"
android:layout_marginEnd="89dp"
android:layout_marginBottom="153dp"
android:text="Button"
app:layout_constraintBottom_toTopOf="#+id/text_home"
app:layout_constraintEnd_toStartOf="#+id/button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="89dp"
android:layout_marginTop="158dp"
android:layout_marginEnd="73dp"
android:layout_marginBottom="150dp"
android:text="Button"
app:layout_constraintBottom_toTopOf="#+id/text_home"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
BlankFragment.java
package eu.sleepy.emptyfragmentbug2;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class BlankFragment extends Fragment {
public Integer color;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_blank, container, false);
FrameLayout frameLayout = root.findViewById(R.id.blankfrag);
frameLayout.setVisibility(View.VISIBLE);
// Inflate the layout for this fragment
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("But it does output");
CreateImage();
}
public void CreateImage() {
FrameLayout frameLayout = getActivity().findViewById(R.id.blankfrag);
frameLayout.setVisibility(View.VISIBLE);
ImageView imageView = new ImageView(getContext());
imageView.setBackgroundColor(color);
LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(300, 500);
layoutParams1.setMargins(25, 0, 0,0);
imageView.setLayoutParams(layoutParams1);
frameLayout.addView(imageView);
}
}
fragment_blank.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"
android:id="#+id/blankfrag"
tools:context=".BlankFragment">
</FrameLayout>
If there is a need for more files, please let me know.
It still executes the code in the called fragment, because it still outputs the System.out.println("But it does output"); in the console as But it does output.
Yet, it doesn't display the fragment when the button is pressed for a second time.
Any help would be really appreciated.

I forgot the fm.popBackStackImmediate(); in the onBackPressed() method in the MainActivity.java. Which, when actually placed in onBackPressed() made everything work perfectly.

Related

handle clickevent in appbar in fragments android studio

I am facing a problem with my custom appbar in my fragment where nothing happens when I click any item in my appbar. I have followed this document to create an appbar in my fragment but still so success.
I have one activity that contains only a fragment container which I switch between fragments from. In one of fragments I want to add a custom fragment owned appbar. I first created a menu like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/settings"
android:title="Settings"
android:icon="#drawable/ic_settings"
app:showAsAction="never">
</item>
<item
android:id="#+id/about"
android:title="About"
android:icon="#drawable/ic_about"
app:showAsAction="never">
</item>
<item
android:id="#+id/logout"
android:title="Logout"
android:icon="#drawable/ic_logout"
app:showAsAction="never">
</item>
</menu>
then in my profile.xml I added a toolbar like this:
<?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=".MainFragments.AddFragment">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/Bar_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#color/darkBlue"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed">
//alot of code in between....
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_prof"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
//more stuff implemented
</RelativeLayout>
however, my menu does not get inflated and if i inflate it via xml nothing happens when I click on any item, what is wrong? Thanks!
here is how my profile fragment looks like:
Edit
here is full profilefragment.java:
package se.umu.moad0012.myservice.MainFragments;
import se.umu.moad0012.myservice.Adapters.FragmentPagerAdapter;
import se.umu.moad0012.myservice.MainActivity;
import se.umu.moad0012.myservice.Models.User;
import se.umu.moad0012.myservice.ProfileFragments.AboutFragment;
import se.umu.moad0012.myservice.ProfileFragments.SettingsFragment;
import se.umu.moad0012.myservice.R;
import se.umu.moad0012.myservice.StartFragments.LoginFragment;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.makeramen.roundedimageview.RoundedImageView;
public class ProfileFragment extends Fragment {
private RoundedImageView mProfileRoundedImageView;
private TextView mPosts, mFollowers, mFollowing, mUserName;
private TabLayout mTabLayout;
private String profileId;
private FirebaseDatabase mFirebaseDatabase;
private ViewPager2 mViewPager2;
private final String[] titles = new String[]{"Posts", "Reviews"};
private final int[] icons = new int[]{R.drawable.ic_grid, R.drawable.feedback};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
//declare variables
declareVariables(v);
//adapter for viewpager2
mViewPager2.setAdapter(new FragmentPagerAdapter(this));
//configure tabs here
tabMediator();
//FirebaseAuth.getInstance().signOut();
//set profile info
setProfileInfo();
return v;
}
private void tabMediator() {
new TabLayoutMediator(mTabLayout, mViewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText(titles[position]);
tab.setIcon(icons[position]);
}
}).attach();
}
private void setProfileInfo() {
mFirebaseDatabase.getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUserName.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void declareVariables(View v) {
mViewPager2 = v.findViewById(R.id.viewpager_profile);
mTabLayout = v.findViewById(R.id.tabLayout_profile);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUserName = v.findViewById(R.id.userNameProfileFragment);
mFollowers = v.findViewById(R.id.followers);
mPosts = v.findViewById(R.id.posts);
mFollowing = v.findViewById(R.id.following);
//mProfileRoundedImageView = v.findViewById(R.id.profileImage);
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
profileId = fUser.getUid();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar_prof);
toolbar.inflateMenu(R.menu.popup_menu_profile);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.settings:
Log.d("TAG", "onOptionsItemSelected: settings");
return true;
case R.id.about:
Log.d("TAG", "onOptionsItemSelected: about");
return true;
case R.id.logout:
Log.d("TAG", "onOptionsItemSelected: logout");
return true;
}
return false;
}
});
}
}
Edit2
I have noticed just now that it works, just that my text is white and thus does not show up. Sorry for any inconvenience.
Put this in your fragment
public class ProfileFragment extends Fragment {
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = view.findViewById(R.id.my_toolbar);
toolbar.inflateMenu(R.menu.your_menu);
toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//handle click
return true;
case R.id.new_pic:
// handle here
return true;
default:
return false;
}
}
});
}
}

My navigation drawer wont open profile fragment with (recyclerview, tablayout and viewpager inside fragment)

all. I'm having a problem.
I am trying to make an application, wherein a navigation-drawer is the source of navigation. In this application, I have some fragments with activities. The problem is, that if I run my profile fragment (which have uses tablayout and recyclerview) in an application for itself, it works. The application when it runs in it's own application.
However, when I attempt to add it to an application, wherein it should be a fragment in a navigation drawer, the application can compile, but when I click on the menuitem in the emulator, it crashes.
I will add the code I have at the moment:
Main Activity
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.content.Intent;
import com.example.sustainably.ui.myprofile.MainActivityProfile;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_friends, R.id.nav_messages, R.id.nav_bookmarks, R.id.nav_myprofile, R.id.nav_discoverforums, R.id.nav_settings, R.id.nav_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public boolean onNavigationItemSelected(MenuItem item) {
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (menuItem.getItemId()) {
case R.id.nav_home:
// code here
break;
case R.id.nav_friends:
// code here
break;
case R.id.nav_messages:
// code here
break;
case R.id.nav_bookmarks:
// code here
break;
case R.id.nav_myprofile:
Intent intent=new Intent(MainActivity.this, MainActivityProfile.class);
startActivity(intent);
break;
case R.id.nav_discoverforums:
//code here
break;
case R.id.nav_settings:
//code here
break;
case R.id.nav_logout:
//code here
break;
}
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
return false;
}
}
and in the profile fragment package i have 6 java classes:
BookmarkModel.java
private String Title;
private int Photo;
public BookmarkModel() {
}
public BookmarkModel(String title, int photo) {
Title = title;
Photo = photo;
}
// Getter
public String getTitle() {
return Title;
}
public int getPhoto() {
return Photo;
}
// Setter
public void setTitle(String title) {
Title = title;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
MainActivityProfile.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.example.sustainably.R;
import com.google.android.material.tabs.TabLayout;
public class MainActivityProfile extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_myprofile);
tabLayout = (TabLayout) findViewById(R.id.tablayout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// Add Fragment Here
adapter.AddFragment(new PublicBookmarkFragment(), "Public Bookmarks");
adapter.AddFragment(new LatestPostsFragment(), "Latest Posts");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_outline_bookmarks_24);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_outline_textsms_24);
}
}
PublicBookmarkFragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sustainably.R;
import java.util.ArrayList;
import java.util.List;
public class PublicBookmarkFragment extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<BookmarkModel> lstBookmarkModel;
public PublicBookmarkFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.public_bookmarks_fragment, container, false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.bookmarks_recyclerview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), lstBookmarkModel);
myrecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
myrecyclerview.setAdapter(recyclerAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstBookmarkModel = new ArrayList<>();
lstBookmarkModel.add(new BookmarkModel("Salad", R.drawable.annapelzer));
lstBookmarkModel.add(new BookmarkModel("Pasta", R.drawable.brookelark_1));
lstBookmarkModel.add(new BookmarkModel("Fruit Salad", R.drawable.brookelark_2));
lstBookmarkModel.add(new BookmarkModel("Smoothies with fruit", R.drawable.brookelark_3));
lstBookmarkModel.add(new BookmarkModel("Soup", R.drawable.cala));
lstBookmarkModel.add(new BookmarkModel("Lobster Salad", R.drawable.davide_cantelli));
lstBookmarkModel.add(new BookmarkModel("Breakfast Toast with Berries", R.drawable.joseph_gonzales));
}
}
RecyclerViewAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sustainably.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<BookmarkModel> mData;
public RecyclerViewAdapter(Context mContext, List<BookmarkModel> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_bookmarks, parent, false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.tv_title.setText(mData.get(position).getTitle());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tv_title;
private ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_title = (TextView) itemView.findViewById(R.id.title_bookmarks);
img = (ImageView) itemView.findViewById(R.id.img_bookmarks);
}
}
}
ViewPagerAdapter
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment (Fragment fragment, String title) {
lstFragment.add(fragment);
lstTitles.add(title);
}
}
fragment_myprofile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myprofile"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<include
layout="#layout/profile_header"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/TabContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tablayout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabIconTint="#color/dark_green"
app:tabIndicatorColor="#color/dark_green"
app:tabInlineLabel="true"
app:tabMode="fixed"
app:tabRippleColor="#color/light_green"
app:tabSelectedTextColor="#color/dark_green"
app:tabTextAppearance="#style/TextAppearance.AppCompat.Small"></com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager_id"></androidx.viewpager.widget.ViewPager>
</LinearLayout>
</LinearLayout>
public_bookmarks_fragment.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="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bookmarks_recyclerview">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
item_bookmarks.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_bookmarks"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/title_bookmarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/dark_green"
android:padding="5dp"
android:text="#string/title"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
I'm new at asking questions in here, so if I missed some information you need, or messed something up, please tell me what you need, and I will provide that aswell. Hope you can help.
For clarification as requested:
Logcat errormessages when I click on the menu
2021-05-06 15:28:54.971 18053-18053/com.example.sustainably E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sustainably, PID: 18053
java.lang.ClassCastException: com.example.sustainably.ui.myprofile.MainActivityProfile cannot be cast to androidx.fragment.app.Fragment
at androidx.fragment.app.Fragment.instantiate(Fragment.java:548)
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390)
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58)
at androidx.navigation.NavController.navigate(NavController.java:1066)
at androidx.navigation.NavController.navigate(NavController.java:944)
at androidx.navigation.NavController.navigate(NavController.java:877)
at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.java:97)
at androidx.navigation.ui.NavigationUI$3.onNavigationItemSelected(NavigationUI.java:453)
at com.google.android.material.navigation.NavigationView$1.onMenuItemSelected(NavigationView.java:217)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
at com.google.android.material.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:416)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="#+id/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.example.sustainably.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/nav_friends"
android:name="com.example.sustainably.ui.friends.FriendsFragment"
android:label="#string/menu_friends"
tools:layout="#layout/fragment_friends" />
<fragment
android:id="#+id/nav_bookmarks"
android:name="com.example.sustainably.ui.bookmarks.BookmarksFragment"
android:label="#string/menu_bookmarks"
tools:layout="#layout/fragment_bookmarks" />
<fragment
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
<fragment
android:id="#+id/nav_discoverforums"
android:name="com.example.sustainably.ui.discoverforums.DiscoverForumsFragment"
android:label="#string/menu_discoverforums"
tools:layout="#layout/fragment_discoverforums" />
<fragment
android:id="#+id/nav_messages"
android:name="com.example.sustainably.ui.messages.MessagesFragment"
android:label="#string/menu_messages"
tools:layout="#layout/fragment_messages" />
</navigation>
The code in it's entirety: https://github.com/CabCabz/SustainablyProblem.git
suggestion:
I analyzed your code, you should not used default navigation drawer setup with mobile_navigation.xml.
Setup drawer menu without mobile_navigation.xml: https://stackoverflow.com/a/67389269/12660050
Solution:
1) As you are using default drawer with mobile_navigation.xml you do not need to
use onNavigationItemSelected() method. So, before doing anything remove it from
your Main Activity.
2) Go to the mobile_navigation.xml file and change tag name fragment to activity in which you are using as a MainActivityProfile.java.
Before:
<fragment
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
After:
<activity
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
By changing only this you can solve your problem!!

Android 4.1.1 - findViewById on RecyclerView returns null in MainActivity

I'm following Android Fundamentals CodeLabs (https://developer.android.com/codelabs/android-training-create-recycler-view?index=..%2F..%2Fandroid-training#3), with minor changes given I am using a more advanced version of Android Studio (4.1.1) and am getting a null recyclerView in MainActivity onCreate method even though the view exists. I've used BasicActivity to start this project. How do I fix this?
Here my XML for fragment_first.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/ourcards_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/button_first"
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_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
and here the MainActivity.java file content:
package com.example.ourcards;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private final LinkedList<String> mCardList = new LinkedList<>();
private RecyclerView mRecyclerView;
private CardListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
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();
}
});
mCardList.addLast("Carta 1");
mCardList.addLast("Carta 2");
// Get a handle to the RecyclerView.
mRecyclerView = findViewById(R.id.ourcards_view);
// Create an adapter and supply the data to be displayed.
mAdapter = new CardListAdapter(this, mCardList);
// Connect the adapter with the RecyclerView.
mRecyclerView.setAdapter(mAdapter);
// Give the RecyclerView a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
EDIT
Here is my activity_main.xml
<?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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.OurCards.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.OurCards.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
<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="#drawable/ic_add_for_fab" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Here content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here my CardListAdapter.java
package com.example.ourcards;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.LinkedList;
public class CardListAdapter extends
RecyclerView.Adapter<CardListAdapter.CardViewHolder> {
private final LinkedList<String> mCardList;
private final LayoutInflater mInflater;
class CardViewHolder extends RecyclerView.ViewHolder {
public final TextView cardItemView;
final CardListAdapter mAdapter;
public CardViewHolder(View itemView, CardListAdapter adapter) {
super(itemView);
cardItemView = itemView.findViewById(R.id.card);
this.mAdapter = adapter;
}
}
public CardListAdapter(Context context,
LinkedList<String> cardList) {
mInflater = LayoutInflater.from(context);
this.mCardList = cardList;
}
#NonNull
#Override
public CardListAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.cardlist_item,
parent, false);
return new CardViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull CardListAdapter.CardViewHolder holder, int position) {
String mCurrent = mCardList.get(position);
holder.cardItemView.setText(mCurrent);
}
#Override
public int getItemCount() {
return mCardList.size();
}
}
and here my FirstFragment.java
package com.example.ourcards;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
}
}
Here my XML for fragment_first.xml:
Note that your filename is fragment_first.xml.
and here the MainActivity.java file content
Your code here seems to have nothing to do with fragment_first.xml. For example, your setContentView() call is loading activity_main.xml.
So, either your RecyclerView needs to be in activity_main.xml, your setContentView() needs to be loading fragment_first, or you otherwise need to synchronize the work in your two code snippets.

Android Switch keeps switching back to what it was before

I made this switch on one of my fragment to switch from the dark theme to light theme. The only problem is that when I leave fragment with the switch on when I go back to the fragment, the switch is off instead of being on like I left it.
Here are the images.
When I go on the fragment: Fragment Switch Off
When I flip the switch: Fragment Switch On
Then I leave the Fragment, then come back to the Fragment: Fragment Switch off while supposed to be on
Her is my code:
SettingsFragment.java:
package com.barzalou.lpapineau.test.ui.settings;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;
import com.barzalou.lpapineau.test.R;
import com.barzalou.lpapineau.test.ui.CheckedChangeCallback;
import java.util.Objects;
public class SettingsFragment extends Fragment {
private SettingsViewModel settingsViewModel;
private CheckedChangeCallback callback = null;
public void onAttach(final Activity activity) {
super.onAttach(activity);
if (activity instanceof CheckedChangeCallback) {
this.callback = (CheckedChangeCallback) activity;
}
}
public void onDetach() {
super.onDetach();
callback = null;
}
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
settingsViewModel = ViewModelProviders.of(this).get(SettingsViewModel.class);
View root = inflater.inflate(R.layout.fragment_settings, container, false);
final TextView textView = root.findViewById(R.id.text_settings);
settingsViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final Switch DarkMode = (Switch) getView().findViewById(R.id.DarkModeSwitch);
final boolean DarkModeVal = DarkMode.isChecked();
Log.d("Dark Mode Checked Value", String.valueOf(DarkModeVal));
DarkMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callback.onCheckedChange(isChecked);
}
});
}
}
SettingsViewModel.java:
package com.barzalou.lpapineau.test.ui.settings;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class SettingsViewModel extends ViewModel {
private MutableLiveData<String> mText;
public SettingsViewModel() {
mText = new MutableLiveData<>();
mText.setValue("Settings");
}
public LiveData<String> getText() {
return mText;
}
}
CheckedChangeCallback.java:
package com.barzalou.lpapineau.test.ui;
public interface CheckedChangeCallback {
void onCheckedChange(boolean isChecked);
}
MainActivity.java:
package com.barzalou.lpapineau.test;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.audiofx.Equalizer;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.barzalou.lpapineau.test.ui.CheckedChangeCallback;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements CheckedChangeCallback {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
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();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_exit) {
finish();
System.exit(0);
}
return false;
}
public void onCheckedChange(boolean isChecked) {
Switch DarkMode = findViewById(R.id.DarkModeSwitch);
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Log.d("Dark Mode Switch State", "On");
DarkMode.setChecked(true);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d("Dark Mode Switch State", "Off");
DarkMode.setChecked(false);
}
}
}
fragment_settings.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:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#fff"
android:padding="10dp"
tools:context=".ui.home.HomeFragment">
<!-- Title -->
<TextView
android:id="#+id/text_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:shadowColor="#bfbfbf"
android:shadowDx="5"
android:shadowDy="5"
android:shadowRadius="0.01"
android:text="#string/this_is_home"
android:textAlignment="center"
android:textColor="#000"
android:textSize="34sp" />
<!-- ...... -->
<!-- Card_View Settings -->
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_outer"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_gravity="center"
android:translationY="60dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="#d3d3d3"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" />
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_inner"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_gravity="center"
android:translationY="60dp"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
card_view:cardBackgroundColor="#f5f5f5"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:elevation="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="#string/Settings"
android:textSize="22sp"/>
<Switch
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/DarkModeSwitch"
android:text="#string/dark_mode"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- .................. -->
<!-- Card_View 2 -->
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:translationY="170dp"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
card_view:cardBackgroundColor="#f5f5f5"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp" />
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:translationY="170dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="#d3d3d3"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" >
</androidx.cardview.widget.CardView>
<!-- ........... -->
</RelativeLayout>
How can this be fixed? I want it to stay flipped while the dark theme is on.
Thanks!
Because fragment recreated, the switch result is lost. So you should save the switch result. For example, SharedPreference.

BottomBar fragments in Android studio

How can I add fragments for each tab in BottomBar in Android studio please a good example like list view or grid view for each tab..thanks
You need to implement SetOnTabSelectListerner.
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
Fragment fragment = null;
Class fragmentClass = null;
switch (tabId) {
case R.id.tab_one:
fragmentClass = TabOneFragment.class;
break;
case R.id.tab_two:
fragmentClass = TabTwoFragment.class;
break;
case R.id.tab_three:
fragmentClass = TabThreeFragment.class;
break;
case R.id.tab_four:
fragmentClass = TabFourFragment.class;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
});
main_activity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements communicator{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(int i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00BBFF"
android:orientation="vertical"
tools:context="com.example.dhanya.myfragmentexample.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentexample.FragmentA"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentexample.FragmentB"
/>
</android.widget.LinearLayout>
fragmentA.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.net.Uri;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
list=(ListView)getActivity().findViewById(R.id.lv);
ArrayAdapter ad=ArrayAdapter.createFromResource(getActivity(),R.array.listval,android.R.layout.simple_list_item_1);
list.setAdapter(ad);
list.setOnItemClickListener(this);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt=(TextView)view;
String str=txt.getText().toString();
comm.respond(position);
}
}
fragmentA.xml
<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="com.example.dhanya.myfragmentexample.FragmentA"
android:background="#FFBB00">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv"/>
</FrameLayout>
fragmentB.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
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.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.textv);
}
public void changedata(int i)
{
Resources res=getResources();
String[] des=res.getStringArray(R.array.desciptions);
// String str=Integer.toString(i);
txt.setText(des[i]);
// txt.setText(str); }}
fragmentB.xml
<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="com.example.dhanya.myfragmentexample.FragmentB"
android:background="#99CC00"
>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textv"/>
</FrameLayout>
strings.xml
<resources>
<string name="app_name">MyFragmentExample</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
<string-array name="listval">
<item>fragments</item>
<item>Activities</item>
<item>Services</item>
<item>Content Providers</item>
</string-array>
<string-array name="desciptions">
<item>A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).</item>
<item>Activities are one of the fundamental building blocks of apps on the Android platform. They serve as the entry point for a user's interaction with an app, and are also central to how a user navigates within an app (as with the Back button) or between apps (as with the Recents button). </item>
<item>A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.</item>
<item>Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Implementing a content provider has many advantages. </item>
</string-array>
</resources>
communicator.java
public interface communicator {
public void respond(int i);
}
//Grid view
main_activity.xml
<ScrollView xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>
</ScrollView>
mainactivity.java
package com.example.harish.mylayoutexamples;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class GridActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
GridView gridView;
static final String[] numbers = new String[] {
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView) findViewById(R.id.gridview1);
// Create adapter to set value for grid view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
/* gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText() , Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText() , Toast.LENGTH_SHORT).show();
}
}
fragments dynamic loading
Main activity. Java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button firstFragment, secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);
// perform setOnClickListener event on First Button
firstFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load First Fragment
loadFragment(new FirstFragment());
}
});
// perform setOnClickListener event on Second Button
secondFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load Second Fragment
loadFragment(new SecondFragment());
}
});
}
private void loadFragment(Fragment fragment) {
// create a FragmentManager
FragmentManager fm = getFragmentManager();
// android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
//fragmentTransaction.add(R.id.firstFragment,fragment);
fragmentTransaction.commit(); // save the changes
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MAIN_ACTIVTY.XML
<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: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=".MainActivity">
<!-- display two Button's and a FrameLayout to replace the Fragment's -->
<Button
android:id="#+id/firstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/button_background_color"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<Button
android:id="#+id/secondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/button_background_color"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
FIRST_FRAGMENT.JAVA
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstFragment extends Fragment {
View view;
Button firstButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_first, container, false);
// get the reference of Button
firstButton = (Button) view.findViewById(R.id.firstButton);
// perform setOnClickListener on first Button
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
FIRST_FRAGMENT>XML
<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"
tools:context="com.abhiandroid.fragmentexample.FirstFragment">
<!--TextView and Button displayed in First Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is First Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/firstButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
SECOND_FRAGMENT>JAVA
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class SecondFragment extends Fragment {
View view;
Button secondButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_second, container, false);
// get the reference of Button
secondButton = (Button) view.findViewById(R.id.secondButton);
// perform setOnClickListener on second Button
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "Second Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
SECOND_FRAGMENT>XML
<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"
tools:context="com.abhiandroid.fragmentexample.SecondFragment">
<!--TextView and Button displayed in Second Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is Second Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/secondButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
main_activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(String i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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="com.example.dhanya.myfragmentcommsimple.MainActivity"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentA">
</fragment>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentB">
</fragment>
</android.widget.LinearLayout>
fragment_A.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.net.Uri;
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.ListView;
public class FragmentA extends Fragment implements View.OnClickListener{
int count=0;
Button bt;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
bt=(Button)getActivity().findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
count++;
comm.respond("The button is clicked "+ count+" times");
}
}
FRAGMET_A.xml
<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="com.example.dhanya.myfragmentcommsimple.FragmentA"
android:background="#99FF00">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn"
android:text="counter"
android:layout_margin="40dp"/>
</FrameLayout>
FRAGMENT_B.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
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.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.tv);
}
public void changedata(String i)
{
txt.setText(i);
}
}
FRAGMENT_B.xml
<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="com.example.dhanya.myfragmentcommsimple.FragmentB"
android:background="#FFBB00">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="haiiii"
android:id="#+id/tv"
android:layout_margin="50dp"/>
</FrameLayout>
COMMUNICATOR.java
package com.example.dhanya.myfragmentcommsimple;
public interface communicator {
public void respond(String i);
}

Categories

Resources