fragment does not start at top - android

My application has a couple tabs of fragments with a viewpager and it does not start on top and I do not know why. Even when I scroll the fragment to the top, refreshing(going back and forth tabs) resets the fragment's start position right above the recyclerview.
fragment2.xml
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:isScrollContainer="false"
android:layout_gravity="fill_vertical"
android:clipToPadding="false"
android:fillViewport="true"
android:scrollbars="none"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="79dp"
android:scaleType="fitXY"
android:src="#drawable/sub4_visual"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="79dp"
android:alpha="0.3"
android:background="#000000"/>
</RelativeLayout>
<TextView
android:id="#+id/frag2_desc"
android:layout_margin="11dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#color/color_333333"
android:text=""/>
<Spinner
android:id="#+id/frag2_dropbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:overScrollMode="ifContentScrolls"
android:scrollbars="none"
android:gravity="left"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_subfrag2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Fragment2.java
public class Fragment2 extends Fragment{
...
public static Frag_BoardContent[] fragsList;
public static RecyclerView mRecyclerView;
public static Frag234_Adapter4 board_adapter;
public Fragment2() {
// 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
final View v = inflater.inflate(R.layout.fragment2, container, false);
tv_frag2Desc = (TextView) v.findViewById(R.id.frag2_desc);
spinner = (Spinner) v.findViewById(R.id.frag2_dropbox);
ArrayList<String> categoryList = new ArrayList<>();
if (connect) makeDynamicArray(categoryList);
adapter = new ArrayAdapter<> (getActivity(), R.layout.activity_board_spinner,categoryList);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(final AdapterView<?> parent, final View view, int position, long id) {
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setNestedScrollingEnabled(false);
board_adapter = new Frag234_Adapter4(MainActivity.context, fragsList);
mRecyclerView.setAdapter(board_adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_subfrag2);
mRecyclerView.setAdapter(board_adapter);
return v;
}
public ArrayList<String> makeDynamicArray(){...}
}

It is a problem about focus. you need to do requestFocus() to your scrollview and
setFocusable(false)
to fragment;

Related

How do I set the click method on CARD VIEW in VIEW PAGER that using ArrayList<> to add the object?

I want to make clicklistener on cardview in my viewpager to startActivity(Intent)
i've tried to make clicklistener with position in setOnPageChangeListener method, but it does not work for me. Please help.
I want to set Intent on cardview.clicklistener, but i don't understand how to set by position, wheter using swith or if method
HERE MY ACTIVITY CODE :
public class Activity extends AppCompatActivity {
ViewPager viewPager;
Adapter adapter;
List<Model> models;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
CardView cardView = findViewById(R.id.cardViewLogin);
//ImageViewPager
models = new ArrayList<>();
models.add(new Model(R.drawable.m,"title", "desc"));
models.add(new Model(R.drawable.d,"title", "desc"));
models.add(new Model(R.drawable.a,"title", "desc"));
adapter = new Adapter(models,this);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
HERE MY ADAPTER CODE :
public class Adapter extends PagerAdapter {
private List<Model> models;
private LayoutInflater layoutInflater;
private Context context;
public Adapter(List<Model> models, Context context) {
this.models = models;
this.context = context;
}
#Override
public int getCount() {
return models.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position)
{
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.item,container,false);
ImageView imageView;
TextView title, desc;
imageView = view.findViewById(R.id.image);
title = view.findViewById(R.id.title);
desc = view.findViewById(R.id.desc);
imageView.setImageResource(models.get(position).getImage());
title.setText(models.get(position).getTitle());
desc.setText(models.get(position).getDesc());
container.addView(view,0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position,
#NonNull Object object) {
container.removeView((View)object);
}
HERE IS MY item.xml 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<androidx.cardview.widget.CardView
android:id="#+id/cardViewLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="20dp"
android:layout_margin="8dp"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="400dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:src="#drawable/hourglass"
android:layout_height="200dp"
android:scaleType="centerInside"
android:layout_margin="10dp"/>
<TextView
android:id="#+id/title"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/image"
android:layout_marginTop="10dp"
android:layout_marginStart="16dp"
android:text="Title"
android:textSize="16sp"/>
<View
android:id="#+id/separator"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/cardview_shadow_start_color"
android:layout_margin="10dp"
android:layout_below="#+id/title"/>
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/separator"
android:layout_marginTop="3dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="20dp"
android:maxLines="3"
android:drawablePadding="10dp"
android:ellipsize="end"
android:text="Description"
android:textSize="16sp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
HERE IS MY XML ACTIVITY LAYOUT CODE :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UserLoginActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundGravity="center"
android:layout_gravity="center"
android:overScrollMode="never"
android:clipToPadding="false">
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>
onClick listener of cardView
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos=viewPager.getCurrentItem();
//used switch case
switch (pos) {
case 0:
//Do whatever you want
break;
case 1:
//Do whatever you want
break;
}
});

Custom ArrayAdapter in Fragment not calling getView()

I'm trying to load a list of objects inside a ListView, that is contained inside a Fragment. But I can't get it to work no matter what.
I've tried to load the same data and the same list directly inside the main activity and it works. But not in the fragment.
Here is my code:
MainActivity - The fragment loads correctly, data from the server is retrieved, everything is ok here.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
setContentView(R.layout.side_menu);
if (SharedPreferencesManager.isAuthenticated(getApplicationContext())) {
ServerComm.getInstance(getApplicationContext()).requestMenuItems(new BaseVolleyCallback() {
#Override
public void onMenuRequest(Menu result) {
leftSideMenu = (SideMenuFragment) getSupportFragmentManager().findFragmentById(R.id.left_side_menu);
leftSideMenu.menuItemList = result.top;
leftSideMenu.test();
}
});
}
}
Fragment: Again, everything looks to be fine
public class SideMenuFragment extends Fragment {
ArrayList<MenuItem> menuItemList;
View mView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.side_menu, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mView = view;
}
public void test(){
MenuItemAdapter adapter = new MenuItemAdapter(getContext(), menuItemList);
ListView listView = (ListView) mView.findViewById(R.id.listView);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final MenuItem item = (MenuItem) parent.getItemAtPosition(position);
MainActivity activity = (MainActivity)getActivity();
activity.loadContent(item);
}
});
}
}
Adapter: - Constructor called with the list of items, getCount() is called with the correct number of items. getView - NOT CALLED.
class MenuItemAdapter extends ArrayAdapter<MenuItem> {
private Context mContext;
private List<MenuItem> menuList = new ArrayList<>();
public MenuItemAdapter(#NonNull Context context, ArrayList<MenuItem> list) {
super(context, 0 , list);
mContext = context;
menuList = list;
}
#Override
public int getCount () {
return menuList.size();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.menu_cell, parent, false);
}
MenuItem item = menuList.get(position);
TextView tvName = (TextView) convertView.findViewById(R.id.itemName);
tvName.setText(item.name);
return convertView;
}
}
main_activity.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment android:name="com.example.dbl.SideMenuFragment"
android:id="#+id/left_side_menu"
android:layout_width="0dp"
android:layout_height="match_parent"
android:elevation="100dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent=".7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
side_menu.xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#color/colorAccent"
android:cacheColorHint="#android:color/transparent"
android:divider="#CCCCCC"
android:dividerHeight="1dp"
android:paddingLeft="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
menu_cell.xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/itemName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Test"
android:textAlignment="center"
android:textColor="#666"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Honestly, I don't know what I could try next.

Fragment with multiple Recycler Views freezes UI

I am creating a Fragment that has 5 horizontal recycler views under a vertical Scroll View but each time this fragment needs to be loaded, the UI freezes for about a second.
I have created an Adapter that sets the Data from 2 different POJOs into the different Recycler Views. I have found out that the line from my code which seems to be causing the issue is the setLayoutManager() because once commented, the fragment loading does not freeze the UI. Apart from that I haven't been able to find out why is that happening when assigning the LayoutManger to the recycler view and what could I do to improve the fragment's performance.
Here is the fragment_home.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.entertainment.logicaldays.planetmovie.views.fragments.HomeFragment"
android:id="#+id/layout"
android:background="#color/colorPrimary">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scroll_view">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/view_pager"
android:layout_marginBottom="5dp">
</android.support.v4.view.ViewPager>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_popular_movies"
android:orientation="horizontal">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_upcoming_movies"
android:orientation="horizontal">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_top_rated_movies"
android:orientation="horizontal">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_popular_tv_shows"
android:orientation="horizontal">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_top_rated_tv_shows"
android:orientation="horizontal">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</ScrollView>
</FrameLayout>
Then I have the recycler_item.xml to bind to the Recycler Views:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/hover_values">
<ImageView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:src="#drawable/ic_launcher_background"
android:layout_gravity="center|top"
android:id="#+id/recycler_image" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:alpha="0"
android:id="#+id/poster_hover_image"
android:layout_centerHorizontal="true"
android:src="#drawable/star"/>
<TextView
android:layout_marginTop="5dp"
android:alpha="0"
android:id="#+id/poster_hover_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/poster_hover_image"
android:fontFamily="#font/theboldfont"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:scrollHorizontally="true"
android:minLines="2"
android:maxLines="2"
android:ellipsize="end"
android:id="#+id/recycler_title"/>
</LinearLayout>
</LinearLayout>
The Adapter which can bind 2 different POJOs into the Recycler Views:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
public Object pojo;
public Context context;
public RecyclerViewAdapter(Context ctx, Object movies) {
this.pojo = movies;
this.context = ctx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ValueAnimator animatorPosterTint = ValueAnimator.ofInt(0, 180);
final ValueAnimator animatorHoverOpacity = ValueAnimator.ofFloat(0, 1);
//When long-pressing the Movie
view.setOnLongClickListener(new LongClickOnPosterItemListerner(view, animatorPosterTint, animatorHoverOpacity));
//When releasing the touch on the movie
view.setOnTouchListener(new ReleasePosterItemListener(view, animatorPosterTint, animatorHoverOpacity));
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(pojo instanceof MovieList) {
holder.title.setText(((MovieList)pojo).results.get(position).title);
Glide.with(context)
.asBitmap()
.load(Utils.BASE_TMDB_POSTER_URL + ((MovieList)pojo).results.get(position).posterPath)
.into(holder.image);
holder.rating.setText(Float.toString(((MovieList)pojo).results.get(position).voteAverage));
}
else{
holder.title.setText(((TVList)pojo).results.get(position).name);
Glide.with(context)
.asBitmap()
.load(Utils.BASE_TMDB_POSTER_URL + ((TVList)pojo).results.get(position).posterPath)
.into(holder.image);
holder.rating.setText(Float.toString(((TVList)pojo).results.get(position).voteAverage));
}
}
#Override
public int getItemCount() {
int count = 0;
if(pojo instanceof MovieList && ((MovieList)pojo).results != null) {
if (((MovieList)pojo).results != null) {
count = ((MovieList)pojo).results.size();
}
}
else{
if (((TVList)pojo).results != null) {
count = ((TVList)pojo).results.size();
}
}
return count;
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView title;
TextView rating;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.recycler_image);
title = itemView.findViewById(R.id.recycler_title);
rating = itemView.findViewById(R.id.poster_hover_text);
}
}
}
And finally we have the HomeFragment.java
public class HomeFragment extends Fragment {
public MainActivity mainActivity;
#BindView(R.id.recycler_popular_movies)
RecyclerView recyclerPopularMovies;
#BindView(R.id.recycler_upcoming_movies)
RecyclerView recyclerUpcomingMovies;
#BindView(R.id.recycler_top_rated_movies)
RecyclerView recyclerTopRatedMovies;
#BindView(R.id.recycler_popular_tv_shows)
RecyclerView recyclerPopularTVShows;
#BindView(R.id.recycler_top_rated_tv_shows)
RecyclerView recyclerTopRatedTVShows;
#BindView(R.id.view_pager)
ViewPager viewPager;
LinkedHashMap<Utils.RequestsToLoad, Boolean> requestsToLoad;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainActivity = (MainActivity) getActivity();
// Inflate the layout into the Fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
ButterKnife.bind(this, v);
startViewPager();
startRecyclerViews();
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void startRecyclerViews(){
displayRecyclerView(recyclerPopularMovies, mainActivity.popularMovies);
displayRecyclerView(recyclerTopRatedMovies, mainActivity.upcomingMovies);
displayRecyclerView(recyclerUpcomingMovies, mainActivity.topRatedMovies);
displayRecyclerView(recyclerPopularTVShows, mainActivity.popularTVShow);
displayRecyclerView(recyclerTopRatedTVShows, mainActivity.topRatedTVShow);
}
private void displayRecyclerView(RecyclerView recyclerView, Object object){
LinearLayoutManager layoutManager = new LinearLayoutManager(mainActivity, LinearLayoutManager.HORIZONTAL, false);
final RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), object);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}
private void startViewPager(){
SwipeAdapter swipeAdapter = new SwipeAdapter(getActivity(), mainActivity.upcomingMovies);
viewPager.setAdapter(swipeAdapter);
}
}
As said before, is there anything that could be causing that delay to load the fragment so that I can improve it?
Thanks in advance

ListView onItemClickListener not working within fragment

I know there is a few dozens of these posts, however even after hours of searching and trying different solutions I have not been able to make my list view work.
The ListView is within a fragment, which also contaains a TextView, and is the reason it is not a ListFragment. This fragment is within an Activity that contains the Fragment as a Framelayout and a Button.
The ListView is getting populated with data, but clicking on one of these items nothing happens.
Activity
public class TurnOnHeadbandActivity extends AppCompatActivity {
private MuseManagerAndroid manager = null;
private final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.turn_on_headband_activity);
// XX this must come before other libmuse API calls; it loads the
// library.
manager = MuseManagerAndroid.getInstance();
manager.setContext(this);
manager.startListening();
handler.post(tickUi);
}
private final Runnable tickUi = new Runnable() {
#Override
public void run() {
List<Muse> pairedMuses = manager.getMuses();
if (pairedMuses.size() >= 1) {
Fragment connectedFragment = new TurnOnHeadbandConnectedFragment();
PairedMuses pairedMusesObject = new PairedMuses(pairedMuses);
Bundle args = new Bundle();
args.putSerializable("pairedMuses", pairedMusesObject);
connectedFragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.turnOnFragment, connectedFragment);
fragmentTransaction.commit();
}
handler.postDelayed(tickUi, 1000 / 60);
}
};
}
XML for Activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/nightsky">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="2">
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:id="#+id/turnOnFragment"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#drawable/faqbutton"
android:layout_margin="10dp"
android:textColor="#color/textColor"
android:text="FAQ"/>
</LinearLayout>
Fragment
public class TurnOnHeadbandConnectedFragment extends Fragment implements OnItemClickListener {
private ListView museListView;
public TurnOnHeadbandConnectedFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.turn_on_headband_connected_fragment, container, false);
Bundle bundle = getArguments();
PairedMuses pairedMuses = (PairedMuses)bundle.getSerializable("pairedMuses");
// Fetch the names and MacAddresses of connected muses and store them in string array
int musesAmount = pairedMuses.getPairedMuses().size();
String[] musesMacAddresses = new String[musesAmount];
for (int i = 0; i < musesAmount; i++) {
musesMacAddresses[i] = String.valueOf(pairedMuses.getPairedMuses().get(i).getName().concat(pairedMuses.getPairedMuses().get(i).getMacAddress()));
}
museListView = (ListView) rootView.findViewById(R.id.museListView);
ArrayAdapter<String> listViewAdapter = new ArrayAdapter<>(getActivity(), R.layout.listview_item, musesMacAddresses);
museListView.setAdapter(listViewAdapter);
museListView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), Activity.class);
intent.putExtra("id", id);
startActivity(intent);
}
}
XML for Fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="10dp"
tools:context="com.musesleep.musesleep.TurnOnHeadbandConnectedFragment"
android:descendantFocusability="blocksDescendants">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:gravity="center"
android:textColor="#color/textColor"
android:text="Select your headband from the list:"/>
<ListView
android:id="#+id/museListView"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
XML for custom ListView Item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="40dp"
android:padding="5dp"
android:background="#40D3D3D3"
android:gravity="center_vertical"
android:textColor="#color/textColor"/>

Fragment overlaying an Activity layout

I'm having problems working with fragments. The problem is: I have a layout in my activity with a ListView. When i select an item in this ListView, instantiates a fragment replacing the activity layout. My result is both fragment and activity contents are showing on screen, overlaying each other. What can I fix that (the fragment just replacing the activity content)? Here is the codes:
activityLayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/activity"
android:orientation="vertical">
<FrameLayout android:id="#+id/fragment_to_replace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:orientation="vertical"
android:layout_gravity="center" >
<TextView android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:text="#string/textView_select_table"
android:textSize="30dp"/>
<ListView android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="#+id/listView"
android:visibility="visible"
android:paddingTop="40dp" />
</FrameLayout>
</LinearLayout>
Activity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
View view = findViewById(R.id.activity);
//Getting the ListView
ListView listView = (ListView) view.findViewById(R.id.listView);
listView.setTextFilterEnabled(true);
//Setting the adapter
listView.setAdapter(new Adapter(this));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Creates a fragment
addFragment();
}
});
}
public void addFragment(){
MyFragment newFragment;
FragmentTransaction newFragmentTransaction = getSupportFragmentManager().beginTransaction();
newFragment = (MyFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment);
if (newFragment == null){
newFragment = new MyFragment(this, getSupportFragmentManager());
newFragmentTransaction.replace(R.id.fragment_to_replace,
new SelectDrinkFragment(this, getSupportFragmentManager()));
newFragmentTransaction.addToBackStack(null);
newFragmentTransaction.commit();
}
}
fragmentLayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:text="#string/textView_two"
android:textSize="20dp"/>
<LinearLayout android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:text="#string/textView" />
<TextView android:id="#+id/textView_two"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"/>
</LinearLayout>
<TextView
android:id="#+id/textView_three"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:text="#string/textView_three"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/listView_two"
android:visibility="visible"
android:paddingTop="40dp" />
</LinearLayout>
Fragment.java
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle saveInstanceState){
View view = inflater.inflate(R.layout.fragment, container, false);
final ListView listView = (ListView) view.findViewById(R.id.listView_two);
CharSequence [] list = getResources().getStringArray(R.array.array);
listView.setAdapter(new ListAdapter(getContext(), list));
return view;
}
ListAdapter.java
public class ListAdapter extends BaseAdapter{
private Context context;
private CharSequence[] drinkArraySize;
public ListAdapter(Context context, CharSequence[] array){
super();
this.context = context;
this.array= array;
}
#Override
public int getCount() {
return array.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public Context getContext(){
return context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout linearLayout = new LinearLayout(getContext());
RadioButton radioButton = new RadioButton(getContext());
radioButton.setText(array[position]);
linearLayout.addView(radioButton);
return linearLayout;
}
}
FragmentTransaction.replace() looks like it only replaces another fragment (and not just any View), so I'm pretty sure this is expected behavior (or at least, I know I've had this happen to me before). I suppose you have a few options:
I don't see in your code anything that would make the fragment's background opaque. You could try that first and see if it helps. If it does, that might be the simplest.
You could just set the other items' visibilities to View.GONE at the same time you perform your transaction, but that has some issues as far as backstack goes.
You could replace the ListView and TextView with a ListFragment instead. This is probably the "best" way to do it, but also is probably the most work.

Categories

Resources