Bottom Navigation Bar in linerylayout does not work - java

I'm trying to make a bottom navigation menu, from how I wrote in the code I only did it that it doesn't appear below. I should put it in this chat app of mine that I am doing so that it always appears after the user has logged in. Is there something I did wrong? Thanks
ChatFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chats, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
usersList = new Stack<>();
if (firebaseUser != null) {
Query reference1 = FirebaseDatabase.getInstance().getReference("Chatlist").child(firebaseUser.getUid()).orderByChild("time");
// Get every user from chatlist reference
reference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chatlist chatlist = snapshot.getValue(Chatlist.class);
usersList.push(chatlist);
}
Collections.reverse(usersList);
chatList();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (task.isSuccessful()) {
String mtoken = task.getResult();
updateToken(mtoken);
Log.d("TAG", mtoken); //Check the generated token.
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
registerForContextMenu(recyclerView);
return view;
}
Chat Layout
<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=".Fragments.ChatsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

It because of your parent group LinearLayout
Try this
<?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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/nav_host_fragment_activity_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation"
/>
<com.google.android.material.appbar.AppBarLayout
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar"
android:background="#color/toolbarDark"
app:popupTheme="#style/MenuStyle">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/profile_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/username"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:textColor="#color/white"
android:textStyle="bold"/>
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabSelectedTextColor="#color/white"
app:tabIndicatorColor="#color/white"
app:tabTextColor="#color/white"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_pager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Inside res folder, create a folder called nav
inside the nav create mobile_navigation.xml and add
<?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/navigation_home">
<fragment
android:id="#+id/navigation_home"
android:name="ChatFragment"
android:label="#string/title_home"
tools:layout="#layout/chat_home" />
<fragment
android:id="#+id/navigation_dashboard"
android:name="DashboardFragment"
android:label="#string/title_dashboard"
tools:layout="#layout/fragment_dashboard" />
<fragment
android:id="#+id/navigation_notifications"
android:name="NotificationsFragment"
android:label="#string/title_notifications"
tools:layout="#layout/fragment_notifications" />
inside MainActivity class or whatever your dashboard class is, add
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new
AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,
R.id.navigation_notifications)
.build();
NavController navController =
Navigation.findNavController(this,
R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this,
navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView,
navController);
}
}
chat fragment
package com.example
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
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 com.example.myapplication.R;
public class ChatFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat,
container, false);
return view.getRootView();
}
}
fragment_chat.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_notifications"
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_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
forum fragment
package com.example
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 com.example.myapplication.R;
public class ForumFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat,
container, false);
return view.getRootView();
}
}
Home fragment
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 com.example.myapplication.R;
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat,
container, false);
return view.getRootView();
}
}

Related

ViewPager2 Inside bottom sheet prevents bottom sheet from vertically scrolling

I have a a persistent bottom sheet behavior in my main activity. The bottom sheet has a container for a fragment with a ViewPager2. The problem is that the ViewPager2 prevents the bottom sheet from vertically scrolling.
I recreated the issue in the a sample app. As you can see from this gif right here, the vertical scrolling doesn't work if it's inside the ViewPager2. Only when I drag all the way down outside the ViewPager2, does it start ducking the bottom sheet. This makes scrolling awkward.
I tried the solution described here but it didn't change anything. The activity's root view is a CoordinatorLayout and the fragment's root view is a LinearLayout with a ConstraintLayout around the ViewPager2.
Here's the main activity layout:
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
<Button
android:id="#+id/expand_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Expand Bottom Sheet" />
</LinearLayout>
<FrameLayout
android:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Here's the fragment inside the bottom sheet's layout:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/purple_500">
<TextView
android:id="#+id/sheet_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:text="This is the sheet fragment"
android:textSize="24sp"
android:textAlignment="center"
android:textColor="#color/white" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="325dp"
android:layout_marginTop="75dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:text="Outside viewpager"
android:textSize="24sp"
android:textAlignment="center"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/view_pager"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Here's the MainActivity:
package com.example.myapplication;
import android.os.Bundle;
import android.widget.Button;
import android.widget.FrameLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomSheetBehavior<FrameLayout> bottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.bottom_sheet));
bottomSheetBehavior.setPeekHeight(200);
bottomSheetBehavior.setHideable(true);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
Button expandButton = findViewById(R.id.expand_button);
expandButton.setOnClickListener(view -> bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED));
Fragment sheetFragment = new SheetFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, sheetFragment).commit();
}
}
And here's the SheetFragment:
package com.example.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
public class SheetFragment extends Fragment {
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_sheet, container, false);
ViewPager2 viewPager = contentView.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter();
viewPager.setAdapter(adapter);
return contentView;
}
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerHolder> {
#NonNull
#Override
public ViewPagerHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = getLayoutInflater().inflate(R.layout.pager_item, parent, false);
return new ViewPagerHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewPagerHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return 5;
}
}
private class ViewPagerHolder extends RecyclerView.ViewHolder {
public ViewPagerHolder(#NonNull View itemView) {
super(itemView);
}
public void bind(int number) {
TextView textView = itemView.findViewById(R.id.pager_textview);
textView.setText(String.format("Inside ViewPager\nPage #%d", number));
}
}
}
Thanks to the great bobekos for helping me with this. His answer was:
Thats because the bottomsheet allow only one scrollable view. So to make it work you must disable the nestedscrolling of the viewpager. The problem is you must
get access to the recylerview inside the viewpager2 there is currently
no get method and the class is final so you can't use inheritance. But
you can do this:
//as extension function
fun ViewPager2.disableNestedScrolling() {
(getChildAt(0) as? RecyclerView)?.apply {
isNestedScrollingEnabled = false
overScrollMode = View.OVER_SCROLL_NEVER
}
}
ps.not tested directly
I translated it to Java:
RecyclerView innerRecyclerView = (RecyclerView) viewPager2.getChildAt(0);
if (innerRecyclerView != null) {
innerRecyclerView.setNestedScrollingEnabled(false);
innerRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
}
Tested and works perfectly.

My buttons and Views do nothing after inflating the layout they are in so avoid null object error

My Main Activity. This is where all my code is.
package com.abhiandroid.tablayoutexample;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
ImageButton imageRopo;
Button btn_show;
InterstitialAd interstitialAd;
AdView adView1,adView2;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater layoutInflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View firstfrag =getLayoutInflater().inflate(R.layout.fragment_first,null);
View thirdfrag =getLayoutInflater().inflate(R.layout.fragment_third,null);
btn_show = (Button)thirdfrag.findViewById(R.id.bt_show);
adView1= (AdView)thirdfrag.findViewById(R.id.ad_view);
adView2= (AdView)thirdfrag.findViewById(R.id.ad_view2);
imageRopo = (ImageButton)firstfrag.findViewById(R.id.buttonropo);
textView = (TextView)firstfrag.findViewById(R.id.testview);
imageRopo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.youtube.com"));
startActivity(intent);
textView.setText("The button works");
}
});
MobileAds.initialize(this, "ca-app-pub-8708219564656739~8048449285");
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("355696115338836").build();
adView1.loadAd(adRequest);
adView2.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId("ca-app-pub-8708219564656739/2401085524");
interstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("355697115338836").build());
btn_show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
interstitialAd.show();
}
});
// get the reference of FrameLayout and TabLayout
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Apps"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.app); // set an icon for the
// first tab
tabLayout.addTab(firstTab); // add the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Products"); // set the Text for the second Tab
secondTab.setIcon(R.drawable.company); // set an icon for the second tab
tabLayout.addTab(secondTab); // add the tab in the TabLayout
// Create a new Tab named "Third"
TabLayout.Tab thirdTab = tabLayout.newTab();
thirdTab.setText("Donate"); // set the Text for the first Tab
thirdTab.setIcon(R.drawable.donation); // set an icon for the first tab
tabLayout.addTab(thirdTab); // add the tab at in the TabLayout
// perform setOnTabSelectedListener event on TabLayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
My activit_main.xml
<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:layout_gravity="center"
android:clickable="true"
android:focusable="true"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/simpleTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#android:color/darker_gray"
app:tabIndicatorColor="#f00"
app:tabSelectedTextColor="#f00"
app:tabTextColor="#000" />
<FrameLayout
android:id="#+id/simpleFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9C27B0">
</FrameLayout>
</LinearLayout>
The buttons and views are in different fragments hence me having to inflate the layouts they are in.
This is my firstfragment.xml. This is where one of my button and one of my TextView is.
<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:background="#ffeadb"
tools:context=".FirstFragment">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f7c5a8"
android:orientation="vertical"
tools:context=".FirstFragment"
tools:layout_editor_absoluteY="1dp">
<TextView
android:id="#+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:fontFamily="#font/roboto_bold"
android:gravity="center"
android:text="Why Choose China when you have the option for Indian?"
android:textSize="37sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="106dp"
android:layout_height="109dp"
android:layout_marginStart="24dp"
android:layout_marginLeft="24dp"
android:layout_marginTop="208dp"
android:layout_marginEnd="281dp"
android:layout_marginRight="281dp"
android:src="#drawable/tiktokl"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:layout_marginTop="148dp"
android:layout_marginEnd="35dp"
android:layout_marginRight="35dp"
android:gravity="center"
android:text="Why Choose Chinese when you can choose an Indian Alternative."
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.255"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="114dp"
android:layout_height="114dp"
android:layout_marginStart="149dp"
android:layout_marginLeft="149dp"
android:layout_marginTop="192dp"
android:layout_marginEnd="148dp"
android:layout_marginRight="148dp"
android:src="#drawable/red_arrow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/buttonropo"
android:layout_width="132dp"
android:layout_height="118dp"
android:layout_marginStart="281dp"
android:layout_marginLeft="281dp"
android:layout_marginTop="183dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:layout_marginBottom="5dp"
android:adjustViewBounds="true"
android:background="#android:color/transparent"
android:baselineAlignBottom="false"
android:cropToPadding="true"
android:src="#drawable/roposoapplog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/testview"
android:layout_width="88dp"
android:layout_height="19dp"
android:layout_marginStart="168dp"
android:layout_marginLeft="168dp"
android:layout_marginTop="336dp"
android:layout_marginEnd="155dp"
android:layout_marginRight="155dp"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
My ThirdFragement Activity file is very empty.
package com.abhiandroid.tablayoutexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FirstFragment extends Fragment {
public FirstFragment() {
// 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
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
Before inflating the layouts, I would get a null object error and after inflating them they no-longer seem to work. They don't do anything. As you can see in my MainActivity.java file I had made is so that when a user clicks a button it redirects them to a website. I even made a TextView that updates itself when the Button is clicked so that I know that the Button is working. I have spent days trying to fix this error and have made no progress. I suspect it is related to some code being wrong while making the fragments.
You should add the logic for your Fragment's views inside your Fragment class.
So, instead of doing the logic for the button in the Activity, do it under the Fragment onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
imageRopo = (ImageButton) v.findViewById(R.id.buttonropo);
textView = (TextView) v.findViewById(R.id.testview);
imageRopo.setOnClickListener(new View.OnClickListener() { ...
// ... and so on
return v;
}

Fragment Does Not Appear In Android

I recently learned about Fragments in Android and was building a notepad application to practice them.
Idea: The idea behind the app is simple. I press the button to add a new note. A CardView Viewgroup turns visible. The fragment will be housed within this CardView.
Problem: When I press the button to add a new note, the fragment does not pop up.
MainActivity.java
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Objects;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private CardView fragmentCardView;
private Button newNoteButton;
private FragmentManager fragmentManager = getSupportFragmentManager();
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setActionBar();
newNoteButton = findViewById(R.id.new_note_button);
fragmentCardView = findViewById(R.id.fragment_cardView);
}
void setActionBar(){
Objects.requireNonNull(getSupportActionBar()).setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.layout_custom_action_bar);
}
void showCreateNoteFragment(){
CreateNoteFragment createNoteFragment = CreateNoteFragment.newInstance();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_cardView, createNoteFragment);
fragmentTransaction.commit();
fragmentCardView.setVisibility(View.VISIBLE);
}
#Override
public void onClick(View v) {
if (v == newNoteButton)
showCreateNoteFragment();
}
}
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"
android:background="#F2F2F2"
tools:context=".MainActivity">
<ListView
android:id="#+id/notes_listView"
android:layout_width="match_parent"
android:layout_height="667dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<Button
android:id="#+id/new_note_button"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_marginTop="27dp"
android:fontFamily="#font/nunito_bold"
android:text="#string/new_note_button_string"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/notes_listView"/>
<androidx.cardview.widget.CardView
android:id="#+id/fragment_cardView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginBottom="100dp"
android:layout_marginStart="25dp"
android:layout_marginEnd="25dp"
android:visibility="invisible"/>
</androidx.constraintlayout.widget.ConstraintLayout>
CreateNoteFragment.java
package com.example.notepadapplication;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class CreateNoteFragment extends Fragment implements View.OnClickListener {
private EditText inputEditText;
public CreateNoteFragment() {
// Required empty public constructor
}
static CreateNoteFragment newInstance(){
return new CreateNoteFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create_note, container, false);
inputEditText = rootView.findViewById(R.id.input_editText);
Button saveButton = rootView.findViewById(R.id.save_button);
saveButton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
String saveButtonText = inputEditText.getText().toString();
}
}
fragment_create_note.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginTop="100dp"
android:layout_marginBottom="100dp"
android:layout_marginStart="25dp"
android:layout_marginEnd="25dp"
android:background="#F2F2F2"
tools:context=".CreateNoteFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/header_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/display_fragment_header_string"
android:layout_marginTop="10dp"
android:textAlignment="center"
android:textSize="20sp"
android:fontFamily="#font/nunito_bold"/>
<View
android:id="#+id/divider_view"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_below="#id/header_textView"
android:background="#000000" />
<EditText
android:id="#+id/input_editText"
android:layout_width="match_parent"
android:layout_height="475dp"
android:layout_below="#id/divider_view"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:padding="10dp"
android:inputType="textMultiLine"
android:gravity="top"
android:background="#FFFFFF"
tools:ignore="Autofill,LabelFor,TextFields" />
<Button
android:id="#+id/save_button"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="#string/save_button_string"
android:fontFamily="#font/nunito_bold"/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Could anyone check why the fragment isn't popping up? Thanks for the help, guys.
P.S.: I think that the application might become a little bloated because of all the ViewGroups that I'm using. If you guys have a better way to design this, by all means, I would love any input.
When I press the button to add a new note, the fragment does not pop up.
This is expected since your button doesn't know what to do when pressed.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setActionBar();
newNoteButton = findViewById(R.id.new_note_button);
// Button will call activity's onClick whenever it's clicked
newNoteButton.setOnClickListener(this);
fragmentCardView = findViewById(R.id.fragment_cardView);
}

Create a search activity like in instagram and twitter

In my project I want the search activity to display two types of data in the search activity (restaurants and meals) and I want to implement it like in Twitter and Instagram, my approach is as follows:
in the search activity I created two fragments with each one having a simple list view, my data gets displayed when launching the app but list views don't display all the items at ones, instead, it makes them scroll (in Instagram search activity it shows the suggested and recent items with full height)
this is the code
search activity:
package com.byshy.light.Activities;
import android.content.pm.ActivityInfo;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;
import com.byshy.light.Fragments.SearchRestaurantsFragment;
import com.byshy.light.R;
import com.byshy.light.SearchMealsFragment;
public class SearchActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.search_restaurants_frag, new SearchRestaurantsFragment()).commit();
FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.search_meals_frag, new SearchMealsFragment()).commit();
}
}
search activity xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.SearchActivity">
<FrameLayout
android:layout_alignParentTop="true"
android:id="#+id/search_container"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:transitionName="search_bar">
<EditText
android:id="#+id/main_screen_search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="7dp"
android:background="#drawable/curved_layout"
android:hint="#string/search"
android:inputType="text"
android:padding="10dp" />
</FrameLayout>
<ScrollView
android:layout_alignParentBottom="true"
android:layout_below="#id/search_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/search_restaurants_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
<FrameLayout
android:id="#+id/search_meals_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
restaurants fragment:
package com.byshy.light.Fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.byshy.light.R;
public class SearchRestaurantsFragment extends Fragment {
ListView lv1;
public SearchRestaurantsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_search_restaurants, container, false);
lv1 = root.findViewById(R.id.search_restaurants_list_view);
String[] items1 = new String[3];
items1[0] = "res1";
items1[1] = "res2";
items1[2] = "res3";
ArrayAdapter<String> aa1 = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, items1);
lv1.setAdapter(aa1);
return root;
}
}
meals fragment:
package com.byshy.light;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SearchMealsFragment extends Fragment {
ListView lv2;
public SearchMealsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_search_meals, container, false);
lv2 = root.findViewById(R.id.search_meals_list_view);
String[] items2 = new String[10];
items2[0] = "meal1";
items2[1] = "meal2";
items2[2] = "meal3";
items2[3] = "meal4";
items2[4] = "meal5";
items2[5] = "meal6";
items2[6] = "meal7";
items2[7] = "meal8";
items2[8] = "meal9";
items2[9] = "meal10";
ArrayAdapter<String> aa2 = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, items2);
lv2.setAdapter(aa2);
return root;
}
}
the fragments xml is basically the same with some id differences so I will post just one:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SearchMealsFragment">
<RelativeLayout
android:id="#+id/small_search_restaurants_bar"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#color/white"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="10dp"
android:text="#string/meals"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="10dp"
android:text="#string/more"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp" />
</RelativeLayout>
<ListView
android:id="#+id/search_meals_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
after not finding anything useful on the internet I came up with a new approach to solve this problem.
my new approach is more efficient and it works by creating a model for search results which contains a string and an integer to indicate if the view is a header or a result, then created a item view that contains a linear layout that gets hidden if the view is a not a header, this logic is done inside the adapter.
this is the code:
this is the search_item.xml
<?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="50dp"
android:orientation="horizontal"
android:clickable="false"
android:focusable="false"
android:foreground="?android:attr/selectableItemBackground">
<LinearLayout
android:orientation="vertical"
android:id="#+id/search_item_back_bar"
android:layout_width="match_parent"
android:layout_centerVertical="true"
android:background="#color/colorPrimary"
android:layout_height="2dp">
</LinearLayout>
<TextView
android:background="#f9f9f9"
android:layout_marginStart="16dp"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:id="#+id/search_result"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/test"
android:textSize="20sp" />
</RelativeLayout>
new searchActivity.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"
android:orientation="vertical"
tools:context=".Activities.SearchActivity">
<FrameLayout
android:id="#+id/search_container"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:transitionName="search_bar">
<EditText
android:id="#+id/main_screen_search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="7dp"
android:background="#drawable/curved_layout"
android:hint="#string/search"
android:inputType="text"
android:padding="10dp" />
</FrameLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/search_activity_results"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
searchActivity.java
package com.byshy.light.Activities;
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.WindowManager;
import com.byshy.light.Adapters.SearchResultsAdapter;
import com.byshy.light.Models.SearchResult;
import com.byshy.light.R;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity {
private RecyclerView searchRV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
searchRV = findViewById(R.id.search_activity_results);
searchRV.setHasFixedSize(true);
searchRV.setLayoutManager(new LinearLayoutManager(this));
ArrayList<SearchResult> results = new ArrayList<>();
results.add(new SearchResult("Restaurants", 1));
results.add(new SearchResult("res1"));
results.add(new SearchResult("res2"));
results.add(new SearchResult("res3"));
results.add(new SearchResult("Meals", 1));
results.add(new SearchResult("meal1"));
results.add(new SearchResult("meal2"));
results.add(new SearchResult("meal3"));
results.add(new SearchResult("meal4"));
results.add(new SearchResult("meal5"));
results.add(new SearchResult("meal6"));
SearchResultsAdapter adapter = new SearchResultsAdapter(results);
searchRV.setAdapter(adapter);
}
}
SearchResultsAdapter.java
package com.byshy.light.Adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.byshy.light.Models.SearchResult;
import com.byshy.light.R;
import java.util.ArrayList;
public class SearchResultsAdapter extends RecyclerView.Adapter<SearchResultsAdapter.SearchResultViewHolder> {
private ArrayList<SearchResult> mData;
public SearchResultsAdapter(ArrayList<SearchResult> data) {
mData = data;
}
#NonNull
#Override
public SearchResultViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.search_item, viewGroup, false);
return new SearchResultViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull SearchResultViewHolder searchResultViewHolder, int i) {
SearchResult searchResult = mData.get(i);
searchResultViewHolder.result.setText(searchResult.getContent());
if (searchResult.getType() == 0) {
searchResultViewHolder.backBar.setVisibility(View.GONE);
searchResultViewHolder.setClickable(true);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) searchResultViewHolder.result.getLayoutParams();
params.leftMargin = 8;
}
}
#Override
public int getItemCount() {
return mData.size();
}
class SearchResultViewHolder extends RecyclerView.ViewHolder {
private TextView result;
private LinearLayout backBar;
private View view;
public SearchResultViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
result = itemView.findViewById(R.id.search_result);
backBar = itemView.findViewById(R.id.search_item_back_bar);
}
public void setClickable(boolean clickable) {
view.setClickable(clickable);
view.setFocusable(clickable);
}
}
}
the end product

Switching between fragments in a layout with BottomNavigationView

This is my first attempt to develop an android application.
I have a MainActivity with ConstraintLayout that has BottomNavigationView. Whenever the first navigation item is selected, I want to display a list of category (displayed in a fragment), then whenever this category is selected, another list will be displayed for items related to that particular category (in another fragment).
I have read in (Android - fragment .replace() doesn't replace content - puts it on top) it states that "static fragments written in XML are unable to be replaced, it has to be in a fragment container", how does it look like?
I tried to create my fragment container, but there is something wrong when I try to get the ListView (grand child of the container)
categoriesListView = getView().findViewById(R.id.categoriesList);
returns null.
MainActivity
package com.alsowaygh.getitdone.view.main;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.services.CategoriesListFragment;
import com.alsowaygh.getitdone.view.services.OnCategorySelectedListener;
import com.alsowaygh.getitdone.view.services.ServicesListFragment;
public class MainActivity extends AppCompatActivity implements OnCategorySelectedListener {
private static final String TAG = "MainActivity";
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.add(R.id.container, categoriesListFragment);
fragmentTransaction.commit();
return true;
case R.id.navigation_bookings:
// mTextMessage.setText(R.string.title_bookings);
return true;
case R.id.navigation_chats:
// mTextMessage.setText(R.string.title_chats);
return true;
case R.id.navigation_settings:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
}
#Override
public void onCategorySelected(String category) {
Log.w(TAG, "Successfully created CategoryListFragment!");
}
}
activity_main layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.main.MainActivity">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Fragment
package com.alsowaygh.getitdone.view.services;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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 com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.main.MainActivity;
public class CategoriesListFragment extends Fragment {
private ListView categoriesListView;
OnCategorySelectedListener categoryListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
//initializing root view first to refer to it
View rootView = inflater.inflate(R.layout.activity_main, container, false);
//initializing ListView
categoriesListView = getView().findViewById(R.id.categoriesList);
//categories list
final String[] categories = {"first category", "second category", "third category", "Fourth category"};
//initializing and adding categories strings to the addapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this.getContext(),
R.layout.category_textview);
for (String c : categories) {
arrayAdapter.add(c);
}
categoriesListView.setAdapter(arrayAdapter);
//implement onListItemClick
categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//retrieve string from categories list at clicked position
categoryListener.onCategorySelected(categories[position]);
}
});
return rootView;
}
#Override //to fource container activity to implement the OnCategorySelectedListener
public void onAttach(Context context) {
super.onAttach(context);
try{
categoryListener = (OnCategorySelectedListener) context;
}catch(ClassCastException e){
throw new ClassCastException(context.toString() + "must implement OnCategorySelectedListener");
}
}
}
fragments container
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</fragment>
</FrameLayout>
Your help will be much appreciated.
You need to add the FrameLayout container within the layout file of the MainActivity(activity_main), onclick of the buttons in BottomNavigationView replace with the fragment. In this way you have a Activity and the fragments are shown within the activity, on click of each menu item you can invoke to replace it with the fragments.
This should resolve your problem.
You need to change the layout as below in activity_main.xml.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.main.MainActivity">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
In the MainActivity code, you need to change as below:
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.replace(R.id.frame, categoriesListFragment);
fragmentTransaction.commit();
return true;
In the fragment layout file change to LinearLayout:
<LinearLayout
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</LinearLayout>
EDIT
In the fragment code, change the layout to the name of the fragment layout file(R.layout.fragment_layout_name).
View rootView = inflater.inflate(R.layout.fragment_layout_name, container, false);
//initializing ListView
categoriesListView = rootView.findViewById(R.id.categoriesList);

Categories