I'm using a ViewPager in a fragment that loads a child fragment per tab, and that is working fine the child fragments are loaded, but the issue is that the tabs themselves, where the tab click-able names go, is not showing, nor is it responding to click events. I reach this screen by selecting an element in a recyclerview in a previous fragment.
The expected layout structure is the following:
But the problem is that, although everything else loads fine and I can side swipe to switch child fragments, the tab bar doesn't load at all and I just get this:
I'm not sure what is causing this, but when I rotate the screen and back, then they appear.
MainActivity class
public class MainActivity extends AppCompatActivity {
private final static int PROFILE_FRAGMENT = 1;
private final static int PRIZES_FRAGMENT = 2;
private final static int STORES_FRAGMENT = 3;
private final static int ABOUT = 4;
private int currentFragment = 3;
private String currentFragmentName = "StoresListFragment";
public int HEADER_IMAGE = R.drawable.avatar;
private DrawerLayout drawer;
private List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
FragmentManager fm = getSupportFragmentManager();
if (getIntent().getStringExtra("STORE_DETAILS") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
}
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
dataList = new ArrayList<>();
addItemsToDataList();
NavDrawerAdapter mAdapter = new NavDrawerAdapter(dataList, this, db.getClientName(), db.getPoints(), HEADER_IMAGE);
mRecyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
drawer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
onTouchDrawer(currentFragment);
final GestureDetector mGestureDetector =
new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
drawer.closeDrawers();
onTouchDrawer(recyclerView.getChildLayoutPosition(child));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
private void addItemsToDataList() {
dataList.add(new DrawerItem(getString(R.string.title_profile), R.mipmap.ic_action_profile));
dataList.add(new DrawerItem(getString(R.string.title_prizes), R.mipmap.ic_action_prizes));
dataList.add(new DrawerItem(getString(R.string.title_stores), R.mipmap.ic_action_sales));
dataList.add(new DrawerItem(getString(R.string.title_about), R.mipmap.ic_action_about));
}
public void openFragment(final Fragment fragment) {
if (!fragment.toString().equalsIgnoreCase(currentFragmentName)) {
// update the transfer content by replacing fragments
currentFragmentName = fragment.toString();
switchContent(fragment);
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitAllowingStateLoss();
}
private void onTouchDrawer(final int position) {
currentFragment = position;
switch (position) {
case PROFILE_FRAGMENT:
openFragment(new ProfileFragment());
setTitle(getString(R.string.title_profile));
break;
case PRIZES_FRAGMENT:
openFragment(new PrizesListFragment());
setTitle(getString(R.string.title_prizes));
break;
case STORES_FRAGMENT:
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
break;
case ABOUT:
openFragment(new AboutFragment());
setTitle(getString(R.string.title_about));
break;
default:
}
}
/*
* helper to switch content with backstack
*/
public void switchContent(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
// add to backstack
.addToBackStack(fragment.getClass().getSimpleName())
.commitAllowingStateLoss();
}
#Override
protected void onResume() {
if (getIntent().getStringExtra("SALES_LIST") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
} else if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
}
super.onResume();
}
}
The fragment in question:
public class StoreDetailsFragment extends Fragment {
private ViewPager viewPager;
private Store storeSelected = null;
private TextView storeName;
private ImageView bannerImage;
private TextView storesubtitle;
public StoreDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_store_details, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.tabanim_viewpager);
TabLayout storeTabLayout = (TabLayout) rootView.findViewById(R.id.tabanim_tabs);
setupViewPager(viewPager);
storeTabLayout.setupWithViewPager(viewPager);
storeTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
Toast.makeText(getActivity(), "Sales List", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getActivity(), "Store Description", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getActivity(), "Store Ratings", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getActivity(), "Images", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
bannerImage = (ImageView) rootView.findViewById(R.id.store_details_banner_image);
storeName = (TextView) rootView.findViewById(R.id.text_store_details_name);
storesubtitle = (TextView) rootView.findViewById(R.id.text_store_details_subtitle);
return rootView;
}
#Override
public void onResume() {
super.onResume();
// Set title
getMainActivity().setTitle(R.string.title_store_details);
}
protected MainActivity getMainActivity() {
return (MainActivity) getActivity();
}
}
Fragment in question's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
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.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="300dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/store_details_banner_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#drawable/white_placeholder"
android:contentDescription=""
android:fitsSystemWindows="true"/>
<LinearLayout
android:id="#+id/smth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="#+id/text_store_details_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="40dp"
android:textColor="#333"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/text_store_details_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="13dp"
android:layout_marginTop="3dp"
android:drawableLeft="#mipmap/ic_action_store_house"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#333"/>
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/transparent"
app:layout_collapseMode="parallax"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabanim_tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:visibility="visible"
app:tabGravity="center"
app:tabIndicatorColor="#F1514A"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#99ffffff"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/tabanim_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
And the ViewPagerAdaper:
public class StoreDetailsViewPagerTabAdaper extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public StoreDetailsViewPagerTabAdaper(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}}
Any help and suggestions are appreciated.
In the end I couldn't find a solution to this and even after consulting some more experienced developers we could only find a workaround, which was just have this be inside an activity instead of a fragment and then the viewpager behaves as expected. I couldn't figure out why it doesn't inside a fragment.
If anyone finds a more suitable answer, go ahead, but until then I'll set this to be the accepted answer.
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
Try this one and initiate your adapter with getChildFragmentManager
I would try to log inside getPageTitle, because I think when you rotate the screen everything is destroyed an the mFragmentTitleList is empty when you redraw the titles, so try to find out what's going on by doing something like:
#Override
public CharSequence getPageTitle(int position) {
Log.d("ViewPagerAdapter", "Displaying title: "+ mFragmentTitleList.get(position));
return mFragmentTitleList.get(position);
}
Your TabLayout might not be showing because you set height to it. Try setting android:layout_height="wrap_content".
You don't have to handle tab clicks manually – if you bind the TabLayout with ViewPager
tabLayout.setupWithViewPager(viewPager);
the listener is created automatically. I would suggest to remove the custom listener.
Related
I'm relatively new to Android Studio and I'm doing an app, one of it's interface's function is to show the data of various user's and I saw various tutorials on how to list data using FirebaseRecyclerAdapter but they are not working. And now I'm trying to do fragments which I don't know how to do yet.
I'd like to know if this code is properly set up to do a fragment.
My MainActivity.java
public class MainActivity extends AppCompatActivity {
private RelativeLayout pills_layout, appoint_layout, add_pills_layout, add_appoints_layout, account_layout, add_button;
private TextView AccountName0, AccountAge0;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private FirebaseRecyclerAdapter adapter;
private View view;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Home();
return true;
case R.id.navigation_pills:
Pills();
return true;
case R.id.navigation_appointment:
Appointment();
return true;
case R.id.navigation_account:
Account();
return true;
}
return false;
}
};
public MainActivity() {
}
private void Account(){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.account);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.VISIBLE);
add_button.setVisibility(View.VISIBLE);
/*Button accountChangePass = findViewById(R.id.AccountChangePass);
accountChangePass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent ChangePW = new Intent(MainActivity.this, ChangePW.class);
startActivity(ChangePW);
}
});*/
}
private void Appointment() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_appoints);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.VISIBLE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.VISIBLE);
}
private void Pills() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_pills);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.VISIBLE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.VISIBLE);
}
private void Home() {
pills_layout.setVisibility(View.VISIBLE);
appoint_layout.setVisibility(View.VISIBLE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.GONE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
Intent VerifyLogin = new Intent(MainActivity.this, Launcher.class);
VerifyLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(VerifyLogin);
}
pills_layout = findViewById(R.id.pills_layout);
appoint_layout = findViewById(R.id.appoint_layout);
add_pills_layout = findViewById(R.id.add_pills);
add_appoints_layout = findViewById(R.id.add_appoints);
//account_layout = findViewById(R.id.accountlist);
AccountName0 = findViewById(R.id.AccountName0);
AccountAge0 = findViewById(R.id.AccountAge0);
add_button = findViewById(R.id.add);
pills_layout.setVisibility(View.VISIBLE);
appoint_layout.setVisibility(View.VISIBLE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.GONE);
recyclerView = findViewById(R.id.accountlist);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public RelativeLayout root;
public TextView txtTitle;
public TextView txtDesc;
public ViewHolder(View itemView) {
super(itemView);
root = itemView.findViewById(R.id.account);
txtTitle = itemView.findViewById(R.id.AccountName0);
txtDesc = itemView.findViewById(R.id.AccountAge0);
}
public void setTxtTitle(String string) {
txtTitle.setText(string);
}
public void setTxtDesc(String string) {
txtDesc.setText(string);
}
}
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(query, new SnapshotParser<Account>() {
#NonNull
#Override
public Account parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Account(snapshot.child("name").getValue().toString(),
snapshot.child("idade").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.account, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
holder.setTxtTitle(model.getName());
holder.setTxtDesc(model.getIdade());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(query, new SnapshotParser<Account>() {
#NonNull
#Override
public Account parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Account(snapshot.child("name").getValue().toString(),
snapshot.child("idade").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.account, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
holder.setTxtTitle(model.getName());
holder.setTxtDesc(model.getIdade());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
adapter.stopListening();
}
};
My Account.java
public class Account {
private String name, idade;
public Account() {
}
public Account(String name, String idade) {
this.name = name;
this.idade = idade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdade() {
return idade;
}
public void setIdade(String idade) {
this.idade = idade;
}
}
My account.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="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/account">
<RelativeLayout
android:id="#+id/AccountUser"
android:layout_width="match_parent"
android:layout_height="163dp"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="15dp"
android:background="#drawable/edit_bg"
android:padding="15dp">
<RelativeLayout
android:id="#+id/AccountImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/AccountInfos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/AccountImage"
android:layout_toEndOf="#id/AccountImage"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp">
<TextView
android:id="#+id/AccountName0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Nome1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/AccountAge0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountName0"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Idade1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="#+id/AccountChangePass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountAge0"
android:text="Mudar Palavra-Passe"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold"
android:textAllCaps="false"
android:padding="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/custom_button"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
the best way to do that in my opinion is using Fragments.
Create 3 fragments:
Just check the checkBox that says " Create layout XML? "
Create a java class and add this code after create 3 fragments:
public class /* class name 1 */ extends FragmentPagerAdapter {
public /* class name 1 */ (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 fragment1= new Fragment1 ();
return fragment1;
case 1:
Fragment2 fragment2 = new Fragment2();
return fragment2 ;
case 2:
Fragment3 fragment3 = new Fragment3 ();
return fragment3 ;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
switch (position){
case 0:
return "/* set a name to fragment1*/";
case 1:
return "/* set a name to fragment2*/";
case 2:
return "/* set a name to fragment3*/";
default:
return null;
}
}
}
Now in your mainActivity.java add this code:
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private /* class name 1 */ mSectionsPagerAdapter;
private TabLayout mTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = findViewById(R.id.main_tabPager);
mSectionsPagerAdapter = new /* class name 1 */(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout = findViewById(R.id.main_tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
}
Now in your mainactivity.xml add this:
<android.support.v4.view.ViewPager
android:id="#+id/main_tabPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"
tools:ignore="UnknownId"></android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:id="#+id/main_tabs">
</android.support.design.widget.TabLayout>
The final result will look like this:
I suppose pills_layout, appoint_layout, .. are your fragment layouts.
Maintaining them by changing their VISIBILITY property is not a good idea.
You have to use the supportFragmentManager instead.
Create a loadFragment method like this
public final boolean loadFragment(#NotNull Fragment fragment) {
this.getSupportFragmentManager().beginTransaction()
.replace(<<id of your fragment container layout>>, fragment, "fragment").commit();
return true;
}
And change your onNavigationItemSelected method to this:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return loadFragment(new HomeFragment());
case R.id.navigation_pills:
return loadFragment(new PillsFragment());
case R.id.navigation_appointment:
return loadFragment(new AppointmentFragment());
case R.id.navigation_account:
return loadFragment(new AccountFragment());
}
return false;
}
};
Now make a seperate class for each fragment and inflate the layout of the right fragment.
here is an example of how your HomeFragment-class has to look like this:
public final class HomeFragment extends Fragment {
#Override
public View onCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.<<your homefragment layout name>>, null);
}
}
I hope it's enough to help you out. I'm sorry if there are little mistakes in syntax, I'm used to code Android in Kotlin. But you will get the idea behind it.
Before put -1 in the score, I tell you that I read all, I repeat ALL the answers about this problem in this site and even in other site, so, if you can give me an hand.
Hi guys, i'm having this problem with my application and I'm wasting too much time in this.
My application is composed by 4 fragments, and I'm having problems with the two with the recyclerview (in fragment_fibra and fragment_adsl).
main.java
public class main extends AppCompatActivity implements
OnFragmentInteractionListener //I HAVE a problem with
OnFragmentInteractionListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(mViewPager); //aggiunta dopo
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(1);
case 1:
return PlaceholderFragment.newInstance(2);
case 2:
return PlaceholderFragment.newInstance(3);
case 3:
return PlaceholderFragment.newInstance(4);
default: return PlaceholderFragment.newInstance(1);
// here i have other problems, so like this the app still work, but if i change something it crash (and I know it's wrong like this)
}
//return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
activity_homepage.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".homepage">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
homepage.java (first fragment)
public class homepage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
fragment_fibra.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fibra"
android:background="#EFEFEF">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:drawablePadding="22dp"
android:gravity="center"
android:hint="#string/cercasugg"
android:textColor="#000000"
android:padding="16dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/ListaFibra"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fibra.java (second fragment)
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public fibra() {
}
public static fibra newInstance(String param1, String param2) {
fibra fragment = new fibra();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_fibra, container, false);
recyclerView = V.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
List<String> input = new ArrayList<>();
for (int i = 0; i < 100; i++) {
input.add("Test" + i);
}
mAdapter = new adFibra(input);
recyclerView.setAdapter(mAdapter);
return V;
/*View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true); //per migliorare performance
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
adFibra adapter = new adFibra(new String[]{"Example One"});
recyclerView.setAdapter(adapter);
return rootView;*/
//return inflater.inflate(R.layout.fragment_fibra, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
try to put
recyclerView.setLayoutManager(llm);
before
recyclerView.setAdapter(adapter);
so it will be
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
MyAdapter adapter = new MyAdapter(new String[]{"Example One", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
recyclerView.setAdapter(adapter);
Happy Coding :D
Are you sure you actually call the fibra fragment?
You are creating a PlaceHolderFragment every time and just inflating different layouts. You don't actually create a fibra fragment, so the recycler is not populated, thus the message.
In your SectionsPagerAdapter, in method getItem, return the fragment instance that corresponds to the position.
For example:
switch (position) {
case 0:
return homepage.newInstance();
case 1:
return fibra.newInstance();
case 2:
return adsl.newInstance();
case 3:
return aiuto.newInstance();
default:
return homepage.newInstance();
}
Remove the PlaceHolderFragment from your main activity. Also homepage is not a fragment, but an activity. All your fragments should look like fibra.
And implement all the fragment interfaces like:
implements fibra.OnFragmentInteractionListener
and create a method to implement it:
#Override
public void onFragmentInteraction(Uri uri) {
// your code here...
}
Unfortunately, I am finding the developer of this project doesn't reply at all. So I am posting here. I am trying to implement this UI on my project but developer has used image in sample code. I need to implement here a fragment from one to another. I have already tried this but this doesn't change my fragment. Below is the code how I implemented.
Note: Below codes are a lot. I posted it to make sure where the problem was. As the documentation and sample project I did all well.
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<io.codetail.widget.RevealLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:autofit="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container1"
android:orientation="vertical"
android:weightSum="2"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/lightbrown"
android:orientation="horizontal"
android:weightSum="2">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2">
<me.grantland.widget.AutofitTextView
android:id="#+id/textBoy"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="32dp"
android:maxLines="1"
android:singleLine="true"
android:typeface="monospace"
android:text="#string/boy"
android:gravity="center_vertical|center_horizontal"
android:textSize="180sp"
autofit:minTextSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/home_boy_one" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/lightGreen"
android:weightSum="2">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2">
<me.grantland.widget.AutofitTextView
android:id="#+id/textGirl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:layout_margin="32dp"
android:maxLines="1"
android:singleLine="true"
android:typeface="monospace"
android:text="#string/girl"
android:textSize="180sp"
autofit:minTextSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/home_girl_one" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</io.codetail.widget.RevealLinearLayout>
Home.java
public class Home extends Fragment implements ScreenShotable {
private View Fragmentone_view;
private Bitmap bitmap;
private AutofitTextView textBoy, textGirl;
private Typeface typeface;
#Nullable
public static Home newInstance() {
Home home = new Home();
return home;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
textBoy = rootView.findViewById(R.id.textBoy);
textGirl = rootView.findViewById(R.id.textGirl);
typeface = Typeface.createFromAsset(getResources().getAssets(), "fonts/trench.otf");
textBoy.setTypeface(typeface);
textGirl.setTypeface(typeface);
Log.d("reachHera","reachhere");
return rootView;
}
#Override
public void takeScreenShot() {
Thread thread = new Thread() {
#Override
public void run() {
try {
Bitmap bitmap = Bitmap.createBitmap(Fragmentone_view.getWidth(),
Fragmentone_view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Fragmentone_view.draw(canvas);
Home.this.bitmap = bitmap;
} catch (Exception ex) {
}
}
};
thread.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.Fragmentone_view = view.findViewById(R.id.container1);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
ContentFragment.java
public class ContentFragment extends Fragment implements ScreenShotable {
public static final String CLOSE = "Close";
public static final String BUILDING = "Building";
public static final String BOOK = "Book";
public static final String PAINT = "Paint";
public static final String CASE = "Case";
public static final String SHOP = "Shop";
public static final String PARTY = "Party";
public static final String MOVIE = "Movie";
private View containerView;
protected ImageView mImageView;
protected int res;
private Bitmap bitmap;
public static ContentFragment newInstance(int resId) {
ContentFragment contentFragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putInt(Integer.class.getName(), resId);
contentFragment.setArguments(bundle);
return contentFragment;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.containerView = view.findViewById(R.id.container);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
res = getArguments().getInt(Integer.class.getName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image_content);
mImageView.setClickable(true);
mImageView.setFocusable(true);
mImageView.setImageResource(res);
return rootView;
}
#Override
public void takeScreenShot() {
Thread thread = new Thread() {
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(containerView.getWidth(),
containerView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
containerView.draw(canvas);
ContentFragment.this.bitmap = bitmap;
}
};
thread.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements ViewAnimator.ViewAnimatorListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private List<SlideMenuItem> list = new ArrayList<>();
private ContentFragment contentFragment;
private ViewAnimator viewAnimator;
private int res = R.drawable.content_music;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentFragment = ContentFragment.newInstance(R.drawable.content_music);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment)
.commit();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
}
});
setActionBar();
createMenuList();
viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
}
private void createMenuList() {
SlideMenuItem menuItem0 = new SlideMenuItem(ContentFragment.CLOSE, R.drawable.icn_close);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(ContentFragment.BUILDING, R.drawable.icn_1);
list.add(menuItem);
SlideMenuItem menuItem2 = new SlideMenuItem(ContentFragment.BOOK, R.drawable.icn_2);
list.add(menuItem2);
SlideMenuItem menuItem3 = new SlideMenuItem(ContentFragment.PAINT, R.drawable.icn_3);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(ContentFragment.CASE, R.drawable.icn_4);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(ContentFragment.SHOP, R.drawable.icn_5);
list.add(menuItem5);
SlideMenuItem menuItem6 = new SlideMenuItem(ContentFragment.PARTY, R.drawable.icn_6);
list.add(menuItem6);
SlideMenuItem menuItem7 = new SlideMenuItem(ContentFragment.MOVIE, R.drawable.icn_7);
list.add(menuItem7);
}
private void setActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
linearLayout.removeAllViews();
linearLayout.invalidate();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
viewAnimator.showMenuContent();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition) {
View view = findViewById(R.id.content_frame);
int finalRadius = Math.max(view.getWidth(), view.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
// ContentFragment contentFragment = ContentFragment.newInstance(this.res);
// getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, contentFragment).commit();
return screenShotable;
}
#Override
public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
switch (slideMenuItem.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
case ContentFragment.BOOK:
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
Home home=Home.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,home);
return replaceFragment(home,position);
default:
return replaceFragment(screenShotable, position);
}
}
#Override
public void disableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(false);
}
#Override
public void enableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.closeDrawers();
}
#Override
public void addViewToContainer(View view) {
linearLayout.addView(view);
}
}
I am using fragNav and bottombar plugin. I am trying to make a fullscreen fragment through a FrameLayout. By default, those plugins came with an actionBar which i delete in my theme with "Theme.AppCompat.Light.NoActionBar". But Once i did this there is still a white bar on top on my screen. When i look at hierarchyView it appears that my FrameLayout is not matching the parent but all my xml are setup with match_parent width and height..
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomBar mBottomBar;
private FragNavController fragNavController;
private final int TAB_FIRST = FragNavController.TAB1;
private final int TAB_SECOND = FragNavController.TAB2;
private final int TAB_THIRD = FragNavController.TAB3;
private final int TAB_FOURTH = FragNavController.TAB4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> fragments = new ArrayList<>(4);
fragments.add(FirstFragment.newInstance(0));
fragments.add(SecondFragment.newInstance(0));
fragments.add(ThirdFragment.newInstance(0));
fragments.add(FourthFragment.newInstance(0));
fragNavController = new FragNavController(getSupportFragmentManager(), R.id.container, fragments);
//BottomBar menu
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItems(R.menu.bottombar_menu);
mBottomBar.setOnMenuTabClickListener(new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
//switch between tabs
switch (menuItemId) {
case R.id.bottomBarItemOne:
fragNavController.switchTab(TAB_FIRST);
break;
case R.id.bottomBarItemSecond:
fragNavController.switchTab(TAB_SECOND);
break;
case R.id.bottomBarItemThird:
fragNavController.switchTab(TAB_THIRD);
break;
case R.id.bottomBarItemFourth:
fragNavController.switchTab(TAB_FOURTH);
break;
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.bottomBarItemOne) {
fragNavController.clearStack();
}
}
});
}
#Override
public void onBackPressed () {
if (fragNavController.getCurrentStack().size() > 1) {
fragNavController.pop();
} else {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
// Necessary to restore the BottomBar's state, otherwise we would
// lose the current tab on orientation change.
mBottomBar.onSaveInstanceState(outState);
}
}
activity_main.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=".MainActivity"
android:id="#+id/container"
android:background="#color/black">
</FrameLayout>
FirstFragment.java
public class FirstFragment extends Fragment {
public class SwipeDeckAdapter extends BaseAdapter {
private List<String> data;
private Context context;
public SwipeDeckAdapter(List<String> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = getActivity().getLayoutInflater();
// normally use a viewholder
v = inflater.inflate(R.layout.card_view, parent, false);
}
((TextView) v.findViewById(R.id.textView2)).setText(data.get(position));
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = (String)getItem(position);
Log.i("MainActivity", item);
}
});
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
final SwipeDeck cardStack = (SwipeDeck) view.findViewById(R.id.swipe_deck);
cardStack.setHardwareAccelerationEnabled(true);
Button btn = (Button) view.findViewById(R.id.undobutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardStack.swipeTopCardLeft(180);
}
});
Button btn2 = (Button) view.findViewById(R.id.joinbutton);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardStack.swipeTopCardRight(180);
}
});
final ArrayList<String> testData = new ArrayList<>();
testData.add("0");
testData.add("1");
testData.add("2");
testData.add("3");
testData.add("4");
final SwipeDeckAdapter adapter = new SwipeDeckAdapter(testData, getActivity() );
cardStack.setAdapter(adapter);
cardStack.setEventCallback(new SwipeDeck.SwipeEventCallback() {
#Override
public void cardSwipedLeft(int position) {
Log.i("MainActivity", "card was swiped left, position in adapter: " + position);
}
#Override
public void cardSwipedRight(int position) {
Log.i("MainActivity", "card was swiped right, position in adapter: " + position);
}
#Override
public void cardsDepleted() {
Log.i("MainActivity", "no more cards");
}
#Override
public void cardActionDown() {
Log.i("MainActivity", "Down");
} ;
#Override
public void cardActionUp() {
Log.i("MainActivity", "Up");
};
});
return view;
}
public static FirstFragment newInstance(int index) {
FirstFragment f = new FirstFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
fragment_first.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:background="#color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="io.MainActivity"
android:fitsSystemWindows="true">
<com.daprlabs.cardstack.SwipeLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<com.daprlabs.cardstack.SwipeDeck
android:id="#+id/swipe_deck"
android:layout_weight="8"
android:layout_width="match_parent"
android:layout_height="0dp"
swipedeck:card_spacing="0dp"
swipedeck:max_visible="3"
swipedeck:render_above="true"
swipedeck:rotation_degrees="15"
swipedeck:opacity_end="0.33">
</com.daprlabs.cardstack.SwipeDeck>
<RelativeLayout
android:id="#+id/rl"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="0dp">
<RelativeLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/undobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Undo"
android:onClick="onClick"/>
<Button
android:id="#+id/joinbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/undobutton"
android:text="Join"
android:onClick="onClick"/>
</RelativeLayout>
</RelativeLayout>
</com.daprlabs.cardstack.SwipeLinearLayout>
In your parent RelativeLayout in fragment_first can you remove the android:fitsSystemWindows="true", I think that may be the cause of the issue.
I'm getting an error stating:
NullPointerException at com.idg.omv.ui.phone.MainActivity.onCreate(MainActivity.java:149)
I've done a bit of debugging and found that fav_up_btn1 = null however I'm not sure exactly what is causing it. I have verified fav_up_btn1 exists in my XML and I'm not sure exactly what else it might be.
JAVA SNIPPET:
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
fav_up_btn1 = (Button) findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(getResources().getDrawable(
R.drawable.fav_up_btn1).getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<com.idg.omv.ui.widget.VideosListView
android:id="#+id/videosListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/footer"
android:layout_width="fill_parent"
android:layout_height="70dip"
android:layout_alignParentBottom="true" >
<ScrollView
android:id="#+id/groupScrollView"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/selstation_up_btn"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
android:background="#color/darkgrey"
android:scaleType="fitXY"
android:src="#drawable/selstation_up_btn" />
</ScrollView>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/scroll_lt_arrow" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/fav_up_btn1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/scroll_rt_arrow" />
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
FULL JAVA SOURCE:
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener,
YouTubeThumbnailView.OnInitializedListener {
// A reference to our list that will hold the video details
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ActionBarDrawerToggle mDrawerToggle;
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "o7VVHhK9zf0";
public static final String VIDEO1_ID = "xVHHJqntuXI";
public static final String VIDEO2_ID = "YWteQj_q3Ro";
public static final String VIDEO3_ID = "83ZgtqTw-mI";
public static final String VIDEO4_ID = "n5wMza29JwI";
private YouTubeThumbnailLoader youTubeThumbnailLoader;
private YouTubeThumbnailView youTubeThumbnailView1;
private YouTubeThumbnailView youTubeThumbnailView2;
private YouTubeThumbnailView youTubeThumbnailView3;
private YouTubeThumbnailView youTubeThumbnailView4;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
private YouTubePlayerView youTubePlayerView;
String TAG = "DEBUG THIS";
private YouTubePlayer youTubePlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
// if(actionBar == null) {
// Log.i(TAG, "ActionBar is null");
// } else {
// Log.i(TAG, "ActionBat is not null");
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
//final ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
if(actionBar == null) { Log.i(TAG,"ActonBar is null");
} else {
Log.i(TAG,"ActionBar is not null");};
Bitmap d = BitmapFactory.decodeResource(this.getResources(),
R.drawable.selstation_up_btn);
ImageView imgView = (ImageView) findViewById(R.id.selstation_up_btn);
imgView.setImageBitmap(d);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
// youTubeThumbnailView1 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview1);
// youTubeThumbnailView1.initialize(API_KEY, this);
fav_up_btn1 = (Button) findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(getResources().getDrawable(
R.drawable.fav_up_btn1).getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
youTubeThumbnailView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO1_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});
youTubeThumbnailView2 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview2);
youTubeThumbnailView2.initialize(API_KEY, this);
youTubeThumbnailView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg1) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO2_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});
youTubeThumbnailView3 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview3);
youTubeThumbnailView3.initialize(API_KEY, this);
youTubeThumbnailView3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg1) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO3_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});
youTubeThumbnailView4 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview4);
youTubeThumbnailView4.initialize(API_KEY, this);
youTubeThumbnailView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg1) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO4_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
youTubePlayer = player;
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
public void onInitializationFailure(YouTubeThumbnailView thumbnailView,
YouTubeInitializationResult error) {
}
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {
youTubeThumbnailLoader = thumbnailLoader;
thumbnailLoader
.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
youTubeThumbnailLoader.setVideo(VIDEO_ID);
}
private final class ThumbnailLoadedListener implements
YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onThumbnailError(YouTubeThumbnailView arg0, ErrorReason arg1) {
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView arg0, String arg1) {
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
// true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] { R.drawable.classical_up_btn,
R.drawable.country_up_btn, R.drawable.dance_up_btn,
R.drawable.hiphop_up_btn };
public int getCount() {
return mImages.length;
}
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
It's because you should add this to your button (look the second line).
<Button
android:id="#+id/fav_up_btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/fav_up_btn1" />
In your code, you didn't provide any id with fav_up_btn1, so when you tried to get the view with this id, it failed