ViewPager on TabLayout not Showing? - android

I am just doing my Daily practice and I had a Problem. I've created Viewpager on Tab Layout but it not worked.
I don't know why, I am just doing like the tutorial on the internet and spend for this problem 2 days. :/
The Tablayout showing all tabs but not with the view (fragment tab).
I'll thank for any help from you all :))))))))
So, here's what I code,
content_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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/content_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.ViewPagerActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/content_home_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimaryAlternate"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="#color/colorPrimary"
app:tabSelectedTextColor="#color/colorPrimary"
app:tabTextColor="#color/colorPrimaryDarkAlternate"
app:tabIconTint="#color/tab_color_selector"
app:tabTextAppearance="#style/tabAllCaps">
<com.google.android.material.tabs.TabItem
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_waterpark"
android:text="#string/waterpark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_home_black_24dp"
android:text="#string/drypark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_human_male_female"
android:text="#string/facilities" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/content_home_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/content_home_tablayout"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_alignParentBottom="true" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
ViewPagerActivity:
package com.ardityo.android.transeraapps.ui.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.home.tabs.drypark.DryParkFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.facilities.FacilitiesFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.waterpark.WaterParkFragment;
import com.google.android.material.tabs.TabLayout;
public class ViewPagerActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter;
WaterParkFragment waterParkFragment;
DryParkFragment dryParkFragment;
FacilitiesFragment facilitiesFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_home);
viewPager = (ViewPager) findViewById(R.id.content_home_viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.content_home_tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager)
{
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// waterParkFragment=new WaterParkFragment();
// dryParkFragment=new DryParkFragment();
// facilitiesFragment=new FacilitiesFragment();
// adapter.addFragment(waterParkFragment,"WaterPark");
// adapter.addFragment(dryParkFragment,"DryPark");
// adapter.addFragment(facilitiesFragment.newInstance(),"Facilities");
adapter.addFragment(WaterParkFragment.newInstance(),"WaterPark");
adapter.addFragment(DryParkFragment.newInstance(),"DryPark");
adapter.addFragment(FacilitiesFragment.newInstance(),"Facilities");
viewPager.setAdapter(adapter);
}
}
DryParkFragment (Same with WaterParkFragment & FacilitiesFragment):
package com.ardityo.android.transeraapps.ui.home.tabs.drypark;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
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.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.settings.SettingsViewModel;
public class DryParkFragment extends Fragment {
public DryParkFragment() {
// Required empty public constructor
}
public static DryParkFragment newInstance() {
Bundle args = new Bundle();
DryParkFragment fragment = new DryParkFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.content_home_2, container, false);
}
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_calls_fragment, menu);
// super.onCreateOptionsMenu(menu, inflater);
// }
}
content_home_2.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.tabs.drypark.DryParkFragment"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mascot_head" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test" />
</LinearLayout>

The problem comes from using ViewPager inside NestedScrollView . This may also happen when you use CoordinatorLayout . You have two options to achieve that .
1 . ViewPager2 :
The first option is to use ViewPager2 . Just take a look :
https://developer.android.com/jetpack/androidx/releases/viewpager2
2 . Use custom ViewPager :
Here is a class for you that can determine its height based on childs.
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int biggestHeightMeasureSpec = 0;
for(int i = 0 ; i < getChildCount() ; i++)
{
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
if(heightMeasureSpec > biggestHeightMeasureSpec)
biggestHeightMeasureSpec = heightMeasureSpec;
}
}
super.onMeasure(widthMeasureSpec, biggestHeightMeasureSpec);
}
}
Finally just use it in your XML layout :
<PATH.TO.YOUR.CustomViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Try using viewpager 2, dont forget to use newest library
-> https://developer.android.com/jetpack/androidx/releases/viewpager2?hl=id

Related

ViewPager2 main activit toolabar is not working

i want to press my custom toolbar button in view activity but i can't do it
how can i bring my custom toolbar on ViewActivity?
pls help me
here is my activity_view
<?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">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbarLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:elevation="0dp"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/alarmToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="center"
app:contentInsetStart="0dp"
app:menu="#menu/alarm_title">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="미운 오리 새끼"
android:fontFamily="#font/applesdgothicneoeb"
android:textColor="#color/black"
android:textSize="25sp" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
here is my ViewActivity
package com.example.test;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import java.util.ArrayList;
import java.util.List;
public class ViewActivity extends AppCompatActivity {
private ViewPager2 pager;
private FragmentStateAdapter pagerAdapter;
private ZoomOutPageTransformer pageTransformer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
Toolbar toolbar = findViewById(R.id.alarmToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
List<Fragment> fragments = new ArrayList<>();
fragments.add(new Duck1Fragment());
fragments.add(new Duck2Fragment());
fragments.add(new Duck3Fragment());
pager = findViewById(R.id.pager);
pagerAdapter = new PagerAdapter(this, fragments);
pager.setAdapter(pagerAdapter);
pager.setPageTransformer(pageTransformer);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alarm_title, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.close:
finish();
return true;
default:
return super .onOptionsItemSelected(item);
}
}
}
here is my Duck1Activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<ImageView
android:id="#+id/imageView"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="70dp"
android:src="#drawable/tale_character"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="150dp"
android:background="#drawable/background"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="161dp"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/ducktale_image"
android:layout_width="275dp"
android:layout_height="275dp"
android:layout_gravity="center"
tools:srcCompat="#tools:sample/avatars" />
</FrameLayout>
<FrameLayout
android:layout_width="300dp"
android:layout_height="175dp"
android:layout_marginBottom="50dp"
android:background="#drawable/background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/duck_tale"
android:layout_width="275dp"
android:layout_height="150dp"
android:scrollbars="vertical"
android:layout_gravity="center"
android:fontFamily="#font/applesdgothicneoeb"
android:text="안녕하세요 이것은 테스트입니다."
android:textAlignment="center"
android:textSize="25sp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
here is my duckFragment
package com.example.test;
import static android.speech.tts.TextToSpeech.ERROR;
import android.content.Context;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import java.util.Locale;
public class Duck1Fragment extends Fragment {
private TextToSpeech tts;
private TextView duck;
Context ct;
public Duck1Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_duck1, container, false);
ct = getActivity().getApplication();
ImageView duck_image = (ImageView) rootView.findViewById(R.id.ducktale_image);
TextView duck = (TextView) rootView.findViewById(R.id.duck_tale);
duck.setText(
);
duck.setMovementMethod(new ScrollingMovementMethod());
tts = new TextToSpeech(ct, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != ERROR) {
tts.setLanguage(Locale.KOREAN);
}
}
});
duck_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts.setSpeechRate(1.0f);
tts.speak(duck.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
return rootView;
}
}
here is my PageAdapter
package com.example.test;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.List;
public class PagerAdapter extends FragmentStateAdapter {
private List<Fragment> fragments;
private static final int NUM_PAGES = 3;
public PagerAdapter(FragmentActivity fragmentActivity, List<Fragment> fragments) {
super(fragmentActivity);
this.fragments = fragments;
}
#NonNull
#Override
public Fragment createFragment(int position) { [tag:tag-name]
if (position == 0) return new Duck1Fragment();
else if (position == 1) return new Duck2Fragment();
else return new Duck3Fragment();
}
#Override
public int getItemCount() {
return NUM_PAGES;
}
}
i want to press my custom button on toolbar..
so u guys can help me?
i serched for google and chatgpt but i cant solve it

Android: Recyclerview inside fragment fetching data from TMDbApi gives error: E/RecyclerView: No adapter attached; skipping layout

I've been struggling with a problem on android. I have an app with a drawer which shows fragments depending on what menu item you click in the drawer.
Here's how my app currently works:
This is the drawer with the menu buttons:
Whenever I click a button, for instance Profile, it will load the correct Fragment:
Now I have this problem with the Recyclerview withing my fragmentview of TV Show
When I click on tv shows I get a white empty layout like this:
And this is what I get in the logcat:
com.example.derwishe.movielist E/RecyclerView: No adapter attached; skipping layout
Here's my code:
Fragment Class:
package com.example.derwishe.movielist;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.derwishe.movielist.Api.OnGetTvShowsCallback;
import com.example.derwishe.movielist.Api.TvShow;
import com.example.derwishe.movielist.Api.TvShowsRepository;
import java.util.List;
public class TvShowFragment extends Fragment {
private TvShowsRepository tvShowsRepository;
private RecyclerView tvShowList;
private ListAdapter adapter;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =
inflater.inflate(R.layout.fragment_tvshow,container,false);
tvShowsRepository = TvShowsRepository.getInstance();
tvShowList = (RecyclerView)view.findViewById(R.id.showsRecyclerView);
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(getActivity());
tvShowList.setLayoutManager(layoutManager);
this.context = context;
tvShowsRepository.getTvShows(new OnGetTvShowsCallback() {
#Override
public void onSuccess(List<TvShow> tvShows) {
adapter = new ListAdapter(tvShows);
tvShowList.setAdapter(adapter);
}
#Override
public void onError() {
Toast.makeText(context, "Please check your internet
connection.", Toast.LENGTH_SHORT).show(); }
});
return view;
}
}
Listadapter class:
package com.example.derwishe.movielist;
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.ImageView;
import android.widget.TextView;
import com.example.derwishe.movielist.Api.TvShow;
import java.util.List;
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.TvShowHolder> {
private List<TvShow> tvShows;
public ListAdapter(List<TvShow> tvShows){
this.tvShows = tvShows;
}
#NonNull
#Override
public TvShowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shows_item,parent,false);
return new TvShowHolder(view);
}
#Override
public void onBindViewHolder(TvShowHolder holder, int i) {
holder.bind(tvShows.get(i));
}
#Override
public int getItemCount() {
return tvShows.size();
}
class TvShowHolder extends RecyclerView.ViewHolder{
TextView showTitle;
public TvShowHolder(View itemView){
super(itemView);
showTitle = itemView.findViewById(R.id.showTitle);
}
public void bind(TvShow tvShow){
showTitle.setText(tvShow.getTitle());
}
}
}
MainActivity class with drawer:
package com.example.derwishe.movielist;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
//Reference naar navigatieview voor click events
NavigationView navigationView =findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_draw_open,R.string.navigation_draw_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//initiele fragment openen bij start
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MovieFragment()).commit();
navigationView.setCheckedItem(R.id.nav_movies);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_movies:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MovieFragment()).commit();
break;
case R.id.nav_tvshows:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TvShowFragment()).commit();
break;
case R.id.nav_watchlist:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new WatchlistFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
case R.id.nav_support:
Toast.makeText(this,"Support message activated",Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
And finally the layout files:
Activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/draw_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_tvshow.xml which holds the recyclerview
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/showsRecyclerView"/>
</RelativeLayout>
And shows_item.xml which represents 1 item in the recyclerviewlist
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_height="50dp"
android:scaleType="fitCenter"
android:layout_margin="8dp"
android:layout_weight="1"
android:id="#+id/showImage"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/showTitle"
android:text="Show Title"
android:textSize="22sp"
android:layout_weight="3"
android:layout_margin="22dp"/>
</LinearLayout>
I think it's because once your fragment's onCreate is first run, the recyclerView isn't assigned an adapter, it's until after you fetch your data (the tv shows) that you set the adapter to your recyclerView.
One way to fix this would be to have a constructor that doesn't take any arguments for your adapter, and a method inside it that would pass in whatever data the recyclerView will need to display. You'd end up with something like this:
public class ListAdapter {
public ListAdapter() {}
public void submitList(final List<TvShow> tvShows) {
this.tvShows = tvShows;
notifyDataChanged();
}
}

fragment stuck - can't go to previous fragment

I have a fragment(A) , where another fragment(B) is being opened . When I press back button it just refreshes the fragment(B) instead of exiting from it and returning to fragment A.
I tried poping back the fragment A in the Activity's onBackPressed callback method but it didn't change a thing :
#Override
public void onBackPressed() {
if(B.active)
{
mFragmentManager.popBackStack( A.TAG , 0);
B.active = false;
}
}
** the active boolean is just something I added as part of the solution. It's initialized to TRUE once the fragment is instantiated.
I don't know how to commit a project!
package com.example.a;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/9.
*/
public class ActivityA extends AppCompatActivity{
#InjectView(R.id.c)
LinearLayout c;
#InjectView(R.id.btn)
TextView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c);
ButterKnife.inject(ActivityA.this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.e, FragA.newInstance(), "A");
// fragmentTransaction.addToBackStack("A");
fragmentTransaction.commitAllowingStateLoss();
}
});
}
}
package com.example.a;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/10.
*/
public class FragA extends Fragment{
private View rootView;
public static FragA newInstance() {
return new FragA();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public FragA() {
}
#InjectView(R.id.a)
LinearLayout a;
#InjectView(R.id.btn)
TextView btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fraga,container,false);
ButterKnife.inject(this,rootView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.e, FragB.newInstance(), "B");
fragmentTransaction.addToBackStack("B");
fragmentTransaction.commitAllowingStateLoss();
}
});
return rootView;
}
}
package com.example.a;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/10.
*/
public class FragB extends Fragment{
private View rootView;
public static FragB newInstance() {
return new FragB();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public FragB() {
}
#InjectView(R.id.b)
LinearLayout b;
#InjectView(R.id.btn)
TextView btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragb,container,false);
ButterKnife.inject(this, rootView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
});
return rootView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/c"
android:background="#4b14b1"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/e"
android:layout_width="match_parent"
android:layout_height="300dp">
</FrameLayout>
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="c"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/a"
android:background="#4b14b1"
android:layout_height="match_parent">
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="A"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/b"
android:background="#4b14b1"
android:layout_height="match_parent">
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="B"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

android won't inflate my fragment

I have the following MainActivity.java
import java.util.Date;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.mydomain.myappname.CardoApplication;
import com.mydomain.myappname.R;
import com.mydomain.myappname.adapters.HomeTabsPagerAdapter;
import com.mydomain.myappname.extensions.SlidingTabLayout;
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private HomeTabsPagerAdapter mPageAdapter;
private Toolbar mToolbar;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViewsClassMembers();
setSupportActionBar(mToolbar);
mPageAdapter = new HomeTabsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPageAdapter);
// Assiging the Sliding Tab Layout View
mTabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
mTabs.setViewPager(mViewPager);
}
private void setViewsClassMembers() {
mViewPager = (ViewPager) findViewById(R.id.pager);
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
}
}
Also have this ActiveFragment.java code
package com.xplete.cardo.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mydomain.myappname.R;
public class ActiveFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_active, container, false);
return v;
}
}
and this is my fragment_active.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_active"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="You Are In Tab active"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</fragment>
When I run it I get this error message:
10-25 13:49:09.014: E/AndroidRuntime(8699):
android.view.InflateException: Binary XML file line #2: Error
inflating class fragment
What am I doing wrong?
You did wrong in XML layout. <fragment>...</fragment>
change it to Layout like <RelativeLayout> ...</RelativeLayout>
Corrected:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_active"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="You Are In Tab active"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

ImageButtons on Pages-Problems (Android)

i have a few pages realized with a PagerAdapter and within that some LinearLayouts, which have some ImageButtons.
My Issue:
i want to get the imagebuttons from all the layouts from my pages on app-start, get the size of them and to resize the images to fill the imagebuttons. Gettting the images and rescaling them works fine, BUT if i do this at the function "onWindowFocusChanged" it only works on the first two pages. The ImageButtons on the third page until the last page are just gone. I assume the problem is that either these pages OR the linear-layouts OR the ImageButtons on these pages are not drawn yet so that it doesnt work.
To prove this i assigned a on-click listener to one of these buttons and do my calculation then and not already at onWindowFocusChanged. This has the same effect, BUT if i click the button after i have wiped over all pages it works on all pages.
Question: how can i make it work on startup for all pages OR without having to wipe over all pages first?
thx for any help in advance!
here is my code:
layout-portrait file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<!-- Row 1-->
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
layout-landscape file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
MyPageAdapter-class:
package com.example.Pagercheck;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MyPageAdapter extends PagerAdapter
{
List<View> pages = null;
public MyPageAdapter(List<View> pages)
{
this.pages = pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public Object instantiateItem(View collection, int position)
{
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view)
{
((ViewPager) collection).removeView((View) view);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void startUpdate(View arg0) {
}
}
My MainActivity-Class:
package com.example.Pagercheck;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private List<View> pages;
private MyPageAdapter pagerAdapter;
private ViewPager viewPager;
private static Context context; //member zum speichern für context für andere Klassen
public static Context getContext(){ return context;} //context für andere Klassen zugänglich machen
//private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
context = this; //context in member speichern
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
pagerAdapter = new MyPageAdapter(pages);
viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
setContentView(viewPager);
for (int i_page=0;i_page<pages.size();i_page++)
{
//Drag-Listener auf ImageButtons:
pages.get(i_page).findViewById(R.id.imageButton1).setOnLongClickListener(new MyLongClickListener());
pages.get(i_page).findViewById(R.id.imageButton1).setOnClickListener(this);
pages.get(i_page).findViewById(R.id.imageButton2).setOnLongClickListener(new MyLongClickListener());
//Drag-Listener auf LinearLayouts:
pages.get(i_page).findViewById(R.id.layout11).setOnDragListener(new MyDragListener());
pages.get(i_page).findViewById(R.id.layout12).setOnDragListener(new MyDragListener());
}
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
//NOTE FOR STACKOVERFLOW
//I COMMENTED THIS OUT SO THAT MY IMAGE BUTTONS DOESNT GET LOST AFTER PAGE 2 SO THAT I CAN TEST MY APP PROPERLY WITH ONCLICK:
// Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
//
// for (int i_page=0;i_page<pages.size();i_page++)
// {
//
// ((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
//
//
// }
}
public void scalePictureToFitButtom(ImageButton img_btn)
{
int width=img_btn.getWidth();
int height=img_btn.getHeight();
BitmapDrawable draw=(BitmapDrawable)img_btn.getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
Bitmap resized = Bitmap.createScaledBitmap(bmp, width-40, height-40, true); //bissle schmaler und niedriger damit man noch den Klickeffekt sieht
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.width=width;
params.height=height;
img_btn.setImageBitmap(resized);
img_btn.setLayoutParams(params);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View view)
{
Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
for (int i_page=0;i_page<pages.size();i_page++)
{
((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
}
Toast einToast = Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT);
einToast.show();
}
}

Categories

Resources