Android BottomNavigationView not shows - java

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().

Related

How to open and close fragment,clicking on the same button in android

how to open and close fragment while clicking on same button . Just like amazon filter button.
when we click first time fragment should apper and then we click on that button again fragment should disapper.
business activity java file
public class business extends AppCompatActivity {
TextView t1, t2;
Button hello;
boolean flag = false;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
hello = findViewById(R.id.hello);
t1=findViewById(R.id.text1);
t2=findViewById(R.id.textt2);
}
#Override
protected void onStart() {
super.onStart();
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
BusinessSort businessSort = new BusinessSort();
fragmentTransaction = manager.beginTransaction();
if (flag) {
fragmentTransaction.remove(businessSort);
flag=false;
} else {
fragmentTransaction.add(R.id.frgmCont, businessSort);
flag=true;
}
fragmentTransaction.commit();
}
});
}
public void f1(String s1, String s2) {
t1.setText(s1);
t2.setText(s2);
}
}
activity_business.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".business"
android:orientation="vertical"
android:id="#+id/businessLinearLayout">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello"
android:id="#+id/hello"
/>
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit2"
android:id="#+id/textt2"/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Fagment file BusinessSort.java
public class BusinessSort extends Fragment {
EditText editText1,editText2;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_business_sort, container, false);
editText1=view.findViewById(R.id.edit1);
editText2=view.findViewById(R.id.edit2);
submit=view.findViewById(R.id.businessfragment_submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
business business = (com.example.project.business) getActivity();
business.f1(s1,s2);
}
});
return view;
}
fragment_business_sort.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BusinessSort"
android:orientation="vertical">
<EditText
android:id="#+id/edit1"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<EditText
android:id="#+id/edit2"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<Button
android:id="#+id/businessfragment_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT"/>
</LinearLayout>
Try replacing the fragment.
fragmentTransaction.replace(R.id.frgmCont, businessSort);
flag = true;
I hope the code is mostly similar to my approach so let me know if the problem still persists so that I will look into it deeper.
public static boolean fragmentState = false;
onClick(){
if(fragmentState){
fragmentState = false;
getActivity().getFragmentManager().beginTransaction().
remove(SomeFragment.this).commit();
}
else{
fragmentState = true;
Fragment someFragment = new SomeFragment();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment );
transaction.addToBackStack(null);
transaction.commit();
}
}
Please make sure that your button is not a part of that fragment.
You need to save the state of the fragment.

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>

Fragments of view pager needs to be programmed from the main activity

I am using a view pager . I have three fragments in it I added a button in one of them and tried to make a method for it in the fragment class but this doesn't work. I tried after that to put the method in the main Activity class and it worked.
this is my MainActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myQuestions:
//newGame();
return true;
case R.id.aboutApp:
//showHelp();
return true;
case R.id.bestStudents:
//showHelp();
return true;
case R.id.myAccount:
//showHelp();
return true;
case R.id.signOut:
mAuth.signOut();
Intent i = new Intent(MainActivity.this, GeneralSignActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(tabPosition != 1){
mViewPager.setCurrentItem(1);
}
else{
this.finishAffinity();
System.exit(0);
}
}
}
and this is my fragment code :
public static LearnFragment newInstance(String param1, String param2) {
LearnFragment fragment = new LearnFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView=inflater.inflate(R.layout.fragment_learn,container,false);
return myView;
}
And this is the xml code of the main activity :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
and this is the fragment xml code :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mk.playAndLearn.fragment.LearnFragment">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="click3"
android:text="click me"/>
</FrameLayout>
and tried to make a method for it in the fragment class but this
doesn't work
If you have added a Button to the Fragment, then you should initialize the Button inside the Fragment with the view prefix and adding the Button inside the Fragment layout too. So:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_learn,container,false);
Button myBtn = myView.findViewById(R.id.thebuttonid);
// use onClickListener here to handle the button
return myView;
}
I suppose you were handling the Button inside the MainActivity class which won't probably work.
You are handling the Button with onClick in the xml so, place the current code inside the Fragment and outside of onCreateView or any other methods:
public void click3(View v) {
switch(v.getId()) {
// do your stuff here
}
}

Android NullPointerException Toolbar.setNavigationOnClickListener null object reference

Here is error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.Toolbar.setNavigationOnClickListener(android.view.View$
OnClickListener)' on a null object reference
it happen on
toolBar.setNavigationOnClickListener(new View.OnClickListener()
imageView.setOnClickListener(new View.OnClickListener()
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener()
have the same problem "null object reference".
my team separate file to fragment and all action listener in MainActivity is broke down but we want to separate to fragment like this, but I can't find why separate file to fragment it will null object reference
Here XML fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="56dp"
android:background="#color/colorPrimary"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/pamba_icon_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp"
app:layout_constraintLeft_toLeftOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/pambaicon"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
android:layout_marginBottom="0dp"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/filter_icon_id"
android:clickable="true"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="48dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintRight_toRightOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:srcCompat="#drawable/filter"
app:layout_constraintVertical_bias="0.533" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPaper_id"
android:layout_below="#id/toolbar">
</android.support.v4.view.ViewPager>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation_id"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_navigation_menu"
app:theme="#style/BottomNavigationTheme"
app:itemBackground="#color/colorGray"/>
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
Here activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.constraint.ConstraintLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Here MainFragment
import...
public class MainFragment extends Fragment {
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
}
and MainActivity
import...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Toolbar toolBar;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView imageView;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle(R.string.title);
drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
imageView = (ImageView) findViewById(R.id.filter_icon_id);
navigationView.setNavigationItemSelectedListener(this);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// set own toolbar
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
} else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "filter click", Toast.LENGTH_SHORT).show();
}
});
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation_id);
// select item from bottom navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.firstpage_id:
Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
break;
case R.id.offergape_id:
Toast.makeText(getApplicationContext(), "offer", Toast.LENGTH_SHORT).show();
break;
case R.id.needpage_id:
Toast.makeText(getApplicationContext(), "need", Toast.LENGTH_SHORT).show();
break;
case R.id.searchpage_id:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
//close drawer when click back
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawer(GravityCompat.END);
}else {
super.onBackPressed();
}
}
// select item from drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.account_detail_id:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
case R.id.trip_detail_id:
Toast.makeText(getApplicationContext(), "detail", Toast.LENGTH_SHORT).show();
break;
case R.id.mail_id:
Toast.makeText(getApplicationContext(), "mail", Toast.LENGTH_SHORT).show();
break;
case R.id.logout_id:
Toast.makeText(getApplicationContext(), "logout", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
edit add navigation_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawe_layout"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<!--set drawer open from right-->
<include layout="#layout/activity_main"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:background="#color/colorGray"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationDrawerStyle"
android:layout_gravity="end"/>
<!--set drawer open from right-->
</android.support.v4.widget.DrawerLayout>
Your setContentView in onCreate is setting it to R.layout.navigation_drawer. You didn't provide an example of that, but instead provided an example of R.layout.fragment_main. I'm thinking you want that one to be your layout instead. So in onCreate in your activity set your content view to that layout instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
... // The rest of your code here
}

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