Home button not working after being pressed - java

I want to access my home page after being pressed. The problem is that after the home button is pressed, you will not be able to go back to it. Despite using the return root function, it still doesn't allow me to access the page after being clicked. This picture shows how I am still pressing on the home button but nothing comes up.
Does anyone know the solution to this problem?
Here is my HomeViewModel:
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home");
}
public LiveData<String> getText() {
return mText;
}
}
Here is my HomeFragment:
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.home_fragment);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}}
Here is my MainDashboard Activity:
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:fitsSystemWindows="true"
app:itemIconTint="#drawable/bottom_navigation_selector"
app:itemTextColor="#color/darker_grey"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="#id/fragment2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:paddingBottom="38sp"
app:layout_constraintTop_toBottomOf="#id/fragment2"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/fragment2"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="#navigation/mobile_navigation"
tools:layout_editor_absoluteX="200dp"
tools:layout_editor_absoluteY="358dp" />
Here is my MainDashboardClass:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__dashboard);
getSupportActionBar().hide();
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
NavController navController = Navigation.findNavController(this, R.id.fragment2);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
Here is my Navigaion Graph:
<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/navigation_home2">
<fragment
android:id="#+id/navigation_account"
android:name="com.login.diamondcharnea.ui.Dashboard_Elements.Account.AccountFragment"
android:label="account.layout"
tools:layout="#layout/fragment_account" />
<fragment
android:id="#+id/navigation_favorites"
android:name="com.login.diamondcharnea.ui.Dashboard_Elements.Favorites.FavoritesFragment"
android:label="favorites.layout"
tools:layout="#layout/fragment_favorites" />
<fragment
android:id="#+id/navigation_home2"
android:name="com.login.diamondcharnea.ui.Dashboard_Elements.home.HomeFragment"
android:label="Home.layout"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/navigation_browse"
android:name="com.login.diamondcharnea.ui.Dashboard_Elements.Browse.BrowseFragment"
android:label="Browse.layout"
tools:layout="#layout/fragment_browse" />
<fragment
android:id="#+id/navigation_bag"
android:name="com.login.diamondcharnea.ui.Dashboard_Elements.bag.BagFragment"
android:label="Bag.layout"
tools:layout="#layout/fragment_bag" />
</navigation>
And here is my BottomNavMenu:
<item
android:id="#+id/navigation_home"
android:icon="#drawable/diamond"
android:title="#string/title_home"
/>
<item
android:id="#+id/navigation_browse"
android:icon="#drawable/iconfinder_search_172546"
android:title="Browse" />
<item
android:id="#+id/navigation_bag"
android:icon="#drawable/shopping_bag"
android:title="#string/bag" />
<item
android:title="#string/favorites"
android:id="#+id/navigation_favorites"
android:icon="#drawable/heart" />
<item
android:title="#string/account"
android:id="#+id/navigation_account"
android:icon="#drawable/user" />
</menu>

Related

Why isn't the Fragment shown in Navigation?

When starting the app, I see neither the recycle view nor the normal fragment. I'm sure that the Navigation switch the fragments but I do not see results. But when I use the saveInstantState I can get the Recycle view to work but I can't switch fragments anymore...
Any help would be great.
Main.java
public class MainActivity extends AppCompatActivity {
MusicStoreService music;
private DrawerLayout drawerLayout;
private NavController navController;
private NavigationView navigationView;
private AppBarConfiguration appBarConfiguration;
public MainActivity() {
super(R.layout.main);
}
#Nullable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
music = new MusicStoreServiceMock();
setContentView(R.layout.main);
Toolbar toolbar = findViewById(R.id.toolbar);
// make sure you import androidx.appcompat.widget.Toolbar !
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
NavHostFragment navHostFragment = (NavHostFragment)
getSupportFragmentManager()
.findFragmentById(R.id.nav_host_fragment_container);
navController = navHostFragment.getNavController();
Set<Integer> topLevelDestinations = new HashSet<>();
topLevelDestinations.add(R.id.productListFragment2);
topLevelDestinations.add(R.id.helloworld);
appBarConfiguration = new AppBarConfiguration.Builder(topLevelDestinations)
.setOpenableLayout(drawerLayout)
.build();
NavigationUI.setupWithNavController(toolbar, navController,
appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.nav_host_fragment_container, ProductListFragment.class, null)
.commit();
System.out.println();
}
}
public MusicStoreService getMusic() {
return music;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<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"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|enterAlways" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/nav_menu"
/>
<!-- attribute app:menu isn't mentioned in the documentation! -->
</androidx.drawerlayout.widget.DrawerLayout>
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:title="MusicStore">
<menu>
<item
android:id="#+id/productListFragment2"
android:title="Products" />
</menu>
</item>
<item android:title="Service">
<menu>
<item
android:id="#+id/helloworld"
android:title="Your Account" />
</menu>
</item>
</group>
</menu>
nav_graph.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/nav_graph"
app:startDestination="#id/productListFragment2">
<fragment
android:id="#+id/productListFragment2"
android:name="musicstore.fragments.ProductListFragment"
android:label="Product List" >
<action
android:id="#+id/action_productListFragment2_to_mainActivity2"
app:destination="#id/mainActivity2" />
</fragment>
<fragment
android:id="#+id/helloworld"
android:name=".musicstore.fragments.helloworld"
android:label="Your Account"
tools:layout="#layout/fragment_helloworld" />
<fragment
android:id="#+id/productDetailFragment2"
android:name="musicstore.fragments.ProductDetailFragment"
android:label="ProductDetailFragment" />
<activity
android:id="#+id/mainActivity2"
android:name="musicstore.MainActivity"
android:label="activity_main"
tools:layout="#layout/activity_main" />
</navigation>
Recycle view fragment:
public class ProductListFragment extends Fragment {
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
System.out.println("Hello");
View v = inflater.inflate(R.layout.product_list_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productlist_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ProductListAdapter pld = new ProductListAdapter(((MainActivity) getActivity()).getMusic(),getContext(),new ClickerListener());
recyclerView.setAdapter(pld);
}
Simple fragment:
public class helloworld extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_helloworld, container, false);
}
}

Control layout object in fragment - getting null object reference

I made a fragment_console.xml and ConsoleFragment.java
In MainActivity.java I create object console_fragment = new ConsoleFragment();
Then OnClickListener runs console_fragment.method();
But it gives error Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
on line
sendButton = v.findViewById(R.id.fragment_console_send_button);
ConsoleFragment.java
public class ConsoleFragment extends Fragment {
View v;
private boolean isVisible;
private Button sendButton;
private TextView consoleText;
private EditText commandText;
public ConsoleFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_console, container, false);
showConsole(v);
return v;
}
public void showConsole(View v){
sendButton = (Button) v.findViewById(R.id.fragment_console_send_button);
consoleText = (TextView) v.findViewById(R.id.fragment_console_log_text);
commandText = (EditText) v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConsoleFragment console_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console_fragment = new ConsoleFragment();
}
public void triggerConsole(View view) { //buton on click
console_fragment.showConsole(view);
}
}
fragment_console.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="wrap_content"
tools:context=".activities.ConsoleFragment">
<TextView
android:id="#+id/fragment_console_log_text"
android:layout_width="match_parent"
android:layout_height="150dp"
android:text="TextView"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent">
<EditText
android:id="#+id/fragment_console_command_text"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="0.75"
android:layout_marginBottom="2dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="#string/console_command"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/fragment_console_send_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="0.25"
android:text="#string/console_send_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<include
android:id="#+id/include"
layout="#layout/activity_top_bar"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragment"
android:name="com.wordfall.wordfallcontroll.activities.ConsoleFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/include2"
app:layout_constraintStart_toStartOf="parent" />
</FrameLayout>
<include
android:id="#+id/include2"
layout="#layout/activity_bottom_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
How to get layout object (buttons, tv etc) to get control on it in fragment class?
public class XFragment extends Fragment {
View v;
private boolean isVisible;
private Button sendButton;
private TextView consoleText;
private EditText commandText;
public XFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_x, container, false);
showConsole(v);
return v;
}
public void showConsole(View v){
sendButton = v.findViewById(R.id.fragment_console_send_button);
consoleText = v.findViewById(R.id.fragment_console_log_text);
commandText = v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
}
In your activity_main.xml file you need to create a container for holding fragments like:
activity_main.xml
<LinearLayout
......
......
....
>
.........
........
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
In your MainActivity.java file inside onCreate method you can do:
MainActivity.java
#Override
protected void onCreate(...){
.....
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ConsoleFragment(), "ConsoleFragment").addToBackStack(null).commit();
}
What view you pass into triggerConsole method from outside fragment? The problem may be in this, you'll try to find controls in layout, which is not part of your fragment. View of your fragment is assigned to global variable v, but now you try to get it from method parameter named v. Try this code.
public void showConsole(){
sendButton = (Button) v.findViewById(R.id.fragment_console_send_button);
consoleText = (TextView) v.findViewById(R.id.fragment_console_log_text);
commandText = (EditText) v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
If you want pass different layouts into same fragment, do it via constructor, not via method parameter, and each time make new instance of fragment.

Android BottomNavigationView not shows

I want to implement BottomNavigationView in my Android app but my code does not displays this BottomNavigationView. Here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavView;
private int startingPosition, newPosition;
private final FragmentHome fragmentHome = new FragmentHome();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
bottomNavView = findViewById(R.id.bottom_navigation);
bottomNavView.setItemIconTintList(null);
bottomNavView.setOnItemSelectedListener(item -> {
showFragment(item.getItemId());
return true;
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragmentHome);
bottomNavView.setSelectedItemId(R.id.action_home);
ft.commit();
}
public void showFragment(int viewId) {
Fragment fragment = null;
switch (viewId) {
case R.id.action_home:
if (bottomNavView.getSelectedItemId() != R.id.action_home) {
fragment = fragmentHome;
newPosition = 0;
}
break;
}
if (fragment != null) {
if (startingPosition > newPosition) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
if (startingPosition < newPosition) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
startingPosition = newPosition;
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_action_bar, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View arg0) {
setItemsVisibility(menu, searchItem, false);
}
#Override
public void onViewDetachedFromWindow(View arg0) {
setItemsVisibility(menu, searchItem, true);
}
});
return super.onCreateOptionsMenu(menu);
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
main_activity.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">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="#menu/menu_bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
menu_bottom_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_home"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/home" />
<item
android:id="#+id/action_words_ranking"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/words_ranking" />
<item
android:id="#+id/action_users_ranking"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/users_ranking" />
<item
android:id="#+id/action_messages"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/messages" />
<item
android:id="#+id/action_notifications"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/notifications" />
</menu>
Not only this BottomNavigationView not displays it even not occupies any vertical space.
Help me please!
EDIT
I also simplified my day/night themes but no effect.
EDIT 2
I know where! There is a problem with ft.replace(R.id.content_frame, fragmentHome); in onCreate. It shows things from fragment but skip BottomNavView from MainActivity But how to solve that?
FragmentHome.java
public class FragmentHome extends Fragment {
private MyViewModel loginViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initBinding();
loginViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String string) {
Toast.makeText(requireActivity(), "cześć " + string, Toast.LENGTH_SHORT).show();
}
});
}
private void initBinding() {
FragmentHomeBinding binding = DataBindingUtil.setContentView((requireActivity()), R.layout.fragment_home);
loginViewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setMyViewModel(loginViewModel);
binding.setLifecycleOwner(this);
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="myViewModel"
type="pl.jawegiel.abc.viewmodel.MyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="#{ ()-> myViewModel.setText() }"/>
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#={myViewModel.text}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Does it return any errors? There is no problem in your code. Could you check the log?
Add app:layout_constraintBottom_toTopOf="#id/bottom_navigation" line to FrameLayout and change it layout_height attribute to 0dp. You must specify limit for FrameLayout, otherwise it can overlay BottomNavigationBar
try to add
layout_constraintTop_toBottomOf="#+id/content_frame"
SOLVED. The problem was with DataBinding in fragment. I needed to move initBinding() and return binding.getRoot() in onCreateView().

Null pointer error when calling communicating between an activity and a fragement

I have been attempting to call a method from my home activity which should fire once a button is clicked on my settings fragment. The result of this button click should call the greenTorso() and swap an image on my avatar fragment. I am currently getting a null pointer error, please see the logcat attached. I'm not even sure if this is the right way to go about this, but been stuck for a couple of days now and hoped someone could help. Thanks in advance.
My home activity:
public class Home extends AppCompatActivity implements SettingsFragment.Communicator {
private TextView name, email;
Button LogoutButton;
UserSessionManager sessionManager;
Button button;
ImageView Torso;
public void communicateWith(){
AvatarFragment avatarFragment = (AvatarFragment)getSupportFragmentManager().findFragmentById(R.id.nav_avatar);
avatarFragment.greenTorso();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
getWindow().setBackgroundDrawableResource(R.drawable.background2); // sets background to background2.png
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // hides keyboard on boot
sessionManager = new UserSessionManager(getApplicationContext());
TextView lblName = (TextView) findViewById(R.id.lblName);
TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
if(sessionManager.checkLogin())
finish();
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
// get name
String name = user.get(UserSessionManager.KEY_NAME);
// get email
String email = user.get(UserSessionManager.KEY_EMAIL);
//lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
lblEmail.setText(Html.fromHtml("Welcome: <b>" + email + "</b>"));
LogoutButton=(Button)findViewById(R.id.LogoutButton);
Toast.makeText(getApplicationContext(),
"User Login Status: " + sessionManager.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
LogoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Clear the User session data
// and redirect user to LoginActivity
sessionManager.logoutUser();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_steps:
selectedFragment = new HomeFragment();
break;
case R.id.nav_avatar:
selectedFragment = new AvatarFragment();
break;
case R.id.nav_settings:
selectedFragment = new SettingsFragment();
break;
}
getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
My settings fragment:
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
private Communicator interfaceImplementor;
public interface Communicator
{
public void communicateWith();
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
this.interfaceImplementor = (Communicator)context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_settings, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ImageView torso = (ImageView) getActivity().findViewById(R.id.Torso);
interfaceImplementor.communicateWith();
}
});
}
}
My avatar fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
return rootView;
}
public void greenTorso()
{
ImageView IV =(ImageView) getActivity().findViewById(R.id.Torso);
IV.setBackgroundResource(R.drawable.torso2green);
}
}
Avatar layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:src="http://schemas.android.com/apk/res-auto"
android:background="#android:color/holo_orange_dark"
>
<ImageView
android:layout_width="500dp"
android:layout_height="530dp"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:id="#+id/Torso"
android:src="#drawable/torso2" >
</ImageView>
</RelativeLayout>
Settings layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#D3D3D3"
android:weightSum="10"
tools:context=".Home">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="100dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shop"
android:textSize="26sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="10dp"/>
<androidx.cardview.widget.CardView
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/cardview"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:layout_marginRight="16dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="15dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="Green Torso"
android:textColor="#color/cardview_dark_background"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/ShopGreenTorso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/torso2green" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="bottom"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/register_button"
android:shadowColor="#color/colorPrimary"
android:text="10,000S Buy"
android:textColor="#color/white">
</Button>
</androidx.cardview.widget.CardView>
My navigation:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_steps"
android:icon="#drawable/ic_directions_walk_black_24dp"
android:title="Steps" />
<item
android:id="#+id/nav_avatar"
android:icon="#drawable/ic_face_black_24dp"
android:title="Avatar" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_build_black_24dp"
android:title="Settings" />
</menu>

Action bar missing when using TabLayout

I've implemented TabLayout from the support library, but it overwrites the ActionBar that i need.
This is the activity that sets it up and inflates the tabs and loads the fragment for the tab.
public class TabsActivity extends android.support.v4.app.FragmentActivity {
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
setTitle("Fuel Logger");
ActionBar a = getActionBar();
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
vp.setAdapter(new FragmentPagerAdapter(
getSupportFragmentManager(), TabsActivity.this
));
TabLayout tabLayout = (TabLayout) findViewById(R.id.fuel_sliding_tabs);
tabLayout.setupWithViewPager(vp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fuel_menu, menu);
MenuItem refresh = menu.findItem(R.id.action_settings);
refresh.setEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
break;
case R.id.action_favorite:
return true;
default:
}
return super.onOptionsItemSelected(item);
}
}
and the xml is just the view pager and tab layout
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
style="#style/FuelTabLayout"
android:id="#+id/fuel_sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1.27"
android:background="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_below="#+id/fuel_sliding_tabs" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#android:drawable/ic_menu_set_as"
app:layout_anchorGravity="bottom|right|end"
app:backgroundTint="#color/colorAccent"
android:layout_gravity="right"
android:cropToPadding="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp" />
</RelativeLayout>
and an example of fragments code which is more or less the same for each fragments class
Public class SummaryFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "SUMM_PAGE";
private int mTab;
public static SummaryFragment newInstance(int page){
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SummaryFragment frag = new SummaryFragment();
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTab = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_summary, null);
return view;
}
first add ToolBar , and use LinearLayout witch have horizontal orientation
and set the in the style NoActionBar
hope its help you

Categories

Resources