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.
Related
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();
}
}
I'm currently making a soundboard app on android studio which has a ton of fragments. The first page on my tab layout is just a normal button view, but my second tabView has another fragmentView within it. The goal is for the first page to just show some normal sounds, and the second tab to have multiple operators to choose specific soundboards for.
Anyways, the app seems to work fine. I can switch from the main tab to the operator tab, and even select operator soundboard pages and be moved to their fragments. However as soon as I try to switch fragments (through my tabview) my app crashes and I get the error:
"Fragment operatorTab{4623fc9} (312d4e58-458c-4f47-8fa3-794fe15f0536)} not attached to a context."**
**at com.jkcarraher.rainbowsixsoundboard.operatorTab.resetAllButtons(operatorTab.java:113)
at com.jkcarraher.rainbowsixsoundboard.operatorTab.access$000(operatorTab.java:31)
at com.jkcarraher.rainbowsixsoundboard.operatorTab$2.onScrollChanged(operatorTab.java:107)
I attached my code below, please let me know if you have any ideas!
MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.Adapter;
import android.widget.TextView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeAds();
makeSixYellow();
//Create ViewPager (that houses all fragments)
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.view_pager);
setUpViewPager(mViewPager);
//Add & customize tabs
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabTextColors(Color.WHITE, Color.WHITE);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setText("Utility");
tabLayout.getTabAt(1).setText("Voice Lines");
checkPageChange();
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new utilityTab(), "Utility");
adapter.addFragment(new voiceLinesView(), "Voice Lines");
viewPager.setAdapter(adapter);
}
private void makeSixYellow(){
TextView textView = findViewById(R.id.titleText);
String text = "R6 Soundboard";
SpannableString ss = new SpannableString(text);
ForegroundColorSpan fcsYellow = new ForegroundColorSpan(Color.rgb(255,236,141));
ss.setSpan(fcsYellow, 1,2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ss);
}
private void initializeAds(){
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
}
private void checkPageChange(){
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
utilityTab.resetAllButtons();
}
#Override
public void onPageSelected(int position) {
utilityTab.resetAllButtons();
}
#Override
public void onPageScrollStateChanged(int state) {
utilityTab.resetAllButtons();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorHeader"
android:theme="#style/AppTheme.AppBarOverlay">
<TextView
android:id="#+id/titleText"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/avenir"
android:gravity="center_horizontal"
android:text="R6 Soundboard"
android:textColor="#FFF"
android:textSize="30sp" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#fff"
android:background="#color/colorHeader" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBody"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
voiceLinesView.java (contains fragments so I can select an operator and it will take me to their soundboard fragment)
package com.jkcarraher.rainbowsixsoundboard;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
public class voiceLinesView extends Fragment {
private SectionsPageAdapter voiceLinesSectionsPageAdapter;
private ViewPager voiceLinesViewPager;
public voiceLinesView() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_voice_lines_view, container, false);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.voiceLinesFrame, new operatorTab());
fragmentTransaction.commit();
return view;
}
}
fragment_voice_lines_view.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".voiceLinesView">
<FrameLayout
android:id="#+id/voiceLinesFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
operatorTab.java
package com.jkcarraher.rainbowsixsoundboard;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import soup.neumorphism.NeumorphCardView;
import soup.neumorphism.ShapeType;
import static android.view.MotionEvent.ACTION_MOVE;
public class operatorTab extends Fragment {
private ScrollView scrollView;
public static RelativeLayout KapkanButton;
public static RelativeLayout GlazButton;
public static RelativeLayout FuzeButton;
public static RelativeLayout TachankaButton;
voiceLinesView voiceLinesView = new voiceLinesView();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_operator_tab, container, false);
//Initialize ScrollView
scrollView = view.findViewById(R.id.operatorScrollView);
//Initialize buttons 1-4
KapkanButton = view.findViewById(R.id.kapkanButton);
GlazButton = view.findViewById(R.id.glazButton);
FuzeButton = view.findViewById(R.id.fuzeButton);
TachankaButton = view.findViewById(R.id.tachankaButton);
//Make buttons 1-6 pressable
initPressableButton(KapkanButton);
initPressableButton(GlazButton);
initPressableButton(FuzeButton);
initPressableButton(TachankaButton);
scrollResetListener();
return view;
}
#SuppressLint("ClickableViewAccessibility")
private void initPressableButton(final RelativeLayout relativeLayout) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorBody));
final Rect r = new Rect();
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
// get the View's Rect relative to its parent
view.getHitRect(r);
// offset the touch coordinates with the values from r
// to obtain meaningful coordinates
final float x = event.getX() + r.left;
final float y = event.getY() + r.top;
if(event.getAction() == MotionEvent.ACTION_DOWN) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorButtonPressed));
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP) {
if (r.contains((int) x, (int) y)) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorBody));
//On Click Up
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.voiceLinesFrame, new kapkanVoiceLines());
fr.commit();
}
}else if(event.getAction() == ACTION_MOVE){
if (!r.contains((int) x, (int) y)) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorBody));
}
return true;
}
return false;
}
});
}
private void scrollResetListener(){
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
resetAllButtons();
}
});
}
public void resetAllButtons(){
KapkanButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
GlazButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
FuzeButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
TachankaButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
}
}
fragment_operator_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".operatorTab">
<ScrollView
android:id="#+id/operatorScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorBody">
<RelativeLayout
android:id="#+id/kapkanButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/kapkanIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_kapkan"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/kapkanIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Kapkan"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/glazButton"
android:layout_below="#+id/kapkanButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/glazIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_glaz"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/glazIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Glaz"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/fuzeButton"
android:layout_below="#+id/glazButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/fuzeIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_fuze"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/fuzeIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Fuze"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/tachankaButton"
android:layout_below="#+id/fuzeButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/tachankaIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_tachanka"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/tachankaIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Tachanka"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
</RelativeLayout>
</ScrollView>
</FrameLayout>
Try to remove the ViewTreeObserver.OnScrollChangedListener when the fragment is destroyed this will avoid any listener that can be attached to a destroyed fragment context not to be triggered whenever you leave and come back to this fragment.
First: make a global field for the listener
public class operatorTab extends Fragment {
...
ViewTreeObserver.OnScrollChangedListener mScrollListener = new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
resetAllButtons();
}
};
Then set the listener wit the created field
private void scrollResetListener(){
scrollView.getViewTreeObserver().addOnScrollChangedListener(mScrollListener);
}
Then remove the listener.. I believe it's typically should be in onDestroyView() >> but also try it in onStop() or onPause if it didn't work
This also will solve memory leak of this listener whenever its callback is triggered after the Fragment's view is destroyed
#Override
public void onDestroyView() {
super.onDestroyView();
scrollView.getViewTreeObserver().removeOnScrollChangedListener(mScrollListener);
}
UPDATE
onStop()/onPause() worked for me
The reason that it didn't work with onDestroyView() because the OperatorTab fragment is a part of one of the ViewPager pages; and by default ViewPager loads a number of close pages in the background to be ready for the next page scroll; loading this pages include some of the fragment lifecycle callbacks like onCreateView, onStart, but not onResume.
When you leave the OperatorTab by scrolling the ViewPager to the next tab/page; onDestroyView() won't be created if the ViewPager decides that OperatorTab is a part of the cached/close pages that the user might return back to it later; and therefore the listener still there and after a few swipes of the pager, the OperatorTab fragment can be detached from the context leaving the listener there with memory leaks...
So, the best way in ViewPager fragment (or any View that loads its fragments in advance) is to stop any listeners once you leave the page, i.e. in onPause or onStop callbacks and not waiting until they are destroyed.
A possible reason for this error is that you are calling getResources() NOT in an Activity without using a context. So, you need to use context.getResources() instead where context may be one of these here . In you instance, I think getContext() will work.
So, I think you should search for all the times you are calling getResources and see if you are using a context or not.
The explanation for this error in a simple way is that you are trying to access the context required in getResources() before the fragment is instantiated.
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);
}
I am trying to create a custom layout for list view in android studio. I was able to successfully get image in the in ListView on runtime but wasn't able to print text in the list view . When i run my program in emulator it runs without any error but it doesn't show any text it only shows image from drawables.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private final static String[] names={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
"A","A","A","A","A","A","A","A","A","A","A","A","A","A",};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView ls = findViewById((R.id.customlistview));
ls.setAdapter(new CustomListAdapter(getApplicationContext(),names,R.drawable.za));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/customlistview"
android:layout_width="409dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
CustomListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomListAdapter extends BaseAdapter {
private final Context context;
private final String[] names;
private final int image;
private final LayoutInflater layoutInflater;
public CustomListAdapter(Context context,String[] names,int image) {
this.context=context;
this.image=image;
this.names=names;
layoutInflater= (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rootview;
rootview = layoutInflater.inflate(R.layout.list_item_layout, null);
TextView tv= rootview.findViewById(R.id.textView);
ImageView iv=rootview.findViewById(R.id.imageView);
tv.setText(names[position]);
iv.setImageResource(image);
return rootview;
}
}
list_item_layout.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:height="70dp"
android:gravity="center"
android:text="TextView"
android:textSize="18sp" />
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_weight="2"
app:srcCompat="#mipmap/ic_launcher" />
</LinearLayout>
The issue is in your list_item_layout file. There is an issue with match_parent in your layout try using below code
<?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="wrap_content"
android:weightSum="3"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:height="70dp"
android:gravity="center"
android:text="TextView"
android:textSize="18sp" />
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="2"
app:srcCompat="#mipmap/ic_launcher" />
The problem was caused by the text colour , changing the colour of textview text in list_item_layout resolved the issue.
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