This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a navigation drawer with two items(each item is a fragment)
The first item "import" ,should display this Fragment:
Here is the Fragment class:
public class Import extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.import_main,container,false);
}
}
it's layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark">
</android.support.constraint.ConstraintLayout>
The second item "Gallery",should display a TabsLayout that contains 2 fragments (TabLeft and TabRight) :
Here is it's classe:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tabs,container,false);
}
and the layout:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_id"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="left"/>
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="right"/>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/pager" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I have tried to implement that but i get a weird error which is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abzo.fragmentstut/com.example.abzo.fragmentstut.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
Here is my MainActivity code:
package com.example.abzo.fragmentstut;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
////////
TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_id);
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
TabPagerAdapter tabsAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAdapter);
//tabLayout.setupWithViewPager(viewPager);
/////
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
getSupportFragmentManager().beginTransaction().replace(R.id.content_main, new Import()).commit();
} else if (id == R.id.nav_gallery) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_main, new Tabs()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My TabPagerAdapter:
package com.example.abzo.fragmentstut;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter {
String [] pagetitle = new String []{"one","two"};
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
TabOne one= new TabOne();
return one;
case 1:
TabTwo two= new TabTwo();
return two;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
and here is one of the 2 tab classes (fragments): (the 2nd tab class is similar)
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_left,container,false);
}
Try this one
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
TabOne one= new TabOne();
return one;
deafault:
TabTwo two= new TabTwo();
return two;
}
}
You have to return Fragment here not null. Always try to use default in switch
Related
Below is my code. Am having a navigation drawer and on click event not working. On clicking on it am having a fragment to load. But its not working.Am having both sliding menu and Tab layout. Does that make any issues?
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
public static int navItemIndex = 0;
private NavigationView navigationView;
private DrawerLayout drawer;
private static final String TAG_SOUP = "Soups";
private static final String TAG_SALADS = "Salads";
private static final String TAG_MAINCRSE = "Main Course";
private static final String TAG_BRKDIN = "Tiffin | Breakfast | Dinner";
private static final String TAG_SNACKS = "Snacks";
private static final String TAG_BEVERAGES = "Beverages";
public static String CURRENT_TAG = TAG_SOUP;
private FloatingActionButton fab;
private Handler mHandler;
private boolean shouldLoadHomeFragOnBackPress = true;
private View navHeader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
// navigationView.setNavigationItemSelectedListener(this);
navHeader = navigationView.getHeaderView(0);
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
//CURRENT_TAG = TAG_SOUP;
loadHomeFragment();
}
viewPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
//fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SoupFragment(), TAG_SOUP);
adapter.addFragment(new SaladFragment(), TAG_SALADS);
adapter.addFragment(new MainCoursesFragment(), TAG_MAINCRSE);
adapter.addFragment(new TifBrkDinFragment(), TAG_BRKDIN);
adapter.addFragment(new SnacksFragment(), TAG_SNACKS);
adapter.addFragment(new BeveragesFragments(), TAG_BEVERAGES);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_SOUP;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// soup
SoupFragment soupFragment = new SoupFragment();
return soupFragment;
case 1:
// salads
SaladFragment saladFragment = new SaladFragment();
return saladFragment;
case 2:
// Main courses
MainCoursesFragment mainCoursesFragment = new MainCoursesFragment();
return mainCoursesFragment;
case 3:
// Breakfast | Tiffin | Dinner
TifBrkDinFragment tifBrkDinFragment = new TifBrkDinFragment();
return tifBrkDinFragment;
case 4:
// Snacks
SnacksFragment snacksFragment = new SnacksFragment();
return snacksFragment;
case 5:
// Beverages
BeveragesFragments beveragesFragments = new BeveragesFragments();
return beveragesFragments;
default:
return new SaladFragment();
}
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_soup:
navItemIndex = 0;
CURRENT_TAG = TAG_SOUP;
break;
case R.id.nav_salads:
navItemIndex = 1;
CURRENT_TAG = TAG_SALADS;
break;
case R.id.nav_main_course:
navItemIndex = 2;
CURRENT_TAG = TAG_MAINCRSE;
break;
case R.id.nav_brktifdin:
navItemIndex = 3;
CURRENT_TAG = TAG_BRKDIN;
break;
case R.id.nav_snacks:
navItemIndex = 4;
CURRENT_TAG = TAG_SNACKS;
break;
case R.id.nav_beverages:
// launch new intent instead of loading fragment
// startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
// drawer.closeDrawers();
navItemIndex = 5;
CURRENT_TAG = TAG_BEVERAGES;
break;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_soup:
fragment = new SoupFragment();
break;
case R.id.nav_salads:
fragment = new SaladFragment();
break;
case R.id.nav_main_course:
fragment = new MainCoursesFragment();
break;
case R.id.nav_brktifdin:
fragment = new TifBrkDinFragment();
break;
case R.id.nav_snacks:
fragment = new SnacksFragment();
break;
case R.id.nav_beverages:
fragment = new BeveragesFragments();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
Try below code ...!
MainActivity.java
package co.in.example.app.tab;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
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.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
Toolbar toolbar;
NavigationView navigationView;
protected TabFragment tabFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tabFragment = new TabFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, tabFragment).commit();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
tabFragment.viewPager.setCurrentItem(0);
} else if (id == R.id.nav_gallery) {
tabFragment.viewPager.setCurrentItem(1);
} else if (id == R.id.nav_slideshow) {
tabFragment.viewPager.setCurrentItem(2);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
TabFragment.java
package co.in.example.app.tab;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class TabFragment extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
public TabHost tabHost;
private int currentTab = 0;
public ViewPager viewPager;
protected TabPagerAdapter pageAdapter;
private List<Fragment> fragments;
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tabhost, null);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
viewPager.addOnPageChangeListener(this);
viewPager.setOffscreenPageLimit(3);
fragments = new ArrayList<Fragment>();
fragments.add(new FragmentImport());
fragments.add(new FragmentGallery());
fragments.add(new FragmentSlideShow());
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pageAdapter = new TabPagerAdapter(getChildFragmentManager(),
fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.imports));
tabHost.addTab(newTab(R.string.gallery));
tabHost.addTab(newTab(R.string.slideshow));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
changeTextColor(i);
}
tabHost.setOnTabChangedListener(this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int tabValue) {
TabSpec tabSpec = tabHost.newTabSpec("");
tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), tabValue));
//tabSpec.setIndicator(tabValue, null);
tabSpec.setContent(new Dummy(getActivity()));
return tabSpec;
}
private View getTabIndicator(Context context, int title) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(title);
return view;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
changeTextColor(i);
}
}
private void changeTextColor(int i) {
if (currentTab == i) {
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setTextColor(getActivity().getResources().getColor(R.color.white));
} else {
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setTextColor(getActivity().getResources().getColor(R.color.tab_un_select));
}
}
public class Dummy implements TabHost.TabContentFactory {
private Context context;
public Dummy(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
return new View(context);
}
}
}
TabPagerAdapter.java
package co.in.example.app.tab;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
public class TabPagerAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
// Create a fragments as you needs
FragmentGallery.java
package co.in.example.app.tab;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentGallery extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_gallery, container, false);
}
}
slide menu item
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="#string/imports" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/slideshow" />
</group>
</menu>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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: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="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<FrameLayout 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/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="co.in.example.app.tab.MainActivity"
tools:showIn="#layout/activity_main" />
</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"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_gravity="center"
android:layout_marginBottom="2dp"
android:gravity="center"
android:maxLines="1"
android:textSize="14sp" />
</LinearLayout>
tabhost.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/actionbar_bg"
android:fadingEdge="none"
android:gravity="center"
android:showDividers="none"
android:paddingTop="5dip"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FFFFFF" />
</LinearLayout>
</TabHost>
// Create fragment xml file
fragment_fragment_import.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="co.in.example.app.tab.FragmentImport">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Import" />
</FrameLayout>
I can't get this to work. The basic app functions as it's supposed to but the ViewPager on one of the layout files doesn't show any fragment at all. I checked the code multiple times but I can't find a bug. When I tried debugging it I noticed that it doesn't even initialize the fragments classes which it's supposed to when you select a tab.
My MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
new GetData(this).execute();
TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("CASUAL"));
tab_layout.addTab(tab_layout.newTab().setText("RANKED"));
tab_layout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tab_layout.getTabCount());
viewPager.setAdapter(adapter);
tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_stats) {
// Handle the camera action
} else if (id == R.id.nav_about) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CasualStats tab1 = new CasualStats();
return tab1;
case 1:
RankedStats tab2 = new RankedStats();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Layout with the ViewPager:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"><![CDATA[
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
]]>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/tab_layout">
</android.support.design.widget.TabLayout>
<view
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="android.support.v4.view.ViewPager"
android:layout_alignParentStart="true"
android:id="#+id/view_pager"
android:layout_below="#+id/tab_layout" />
</RelativeLayout>
The classes for the tab fragments which are supposed to be displayed in the ViewPager are just normal auto generated Android Studio fragment classes.
One of the fragments:
public class CasualStats extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CasualStats() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CasualStats.
*/
// TODO: Rename and change types and number of parameters
public static CasualStats newInstance(String param1, String param2) {
CasualStats fragment = new CasualStats();
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);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_casual_stats, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.anzel.r6s.CasualStats">
<!-- TODO: Update blank fragment layout -->
<TextView
android:text="1st fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="28dp"
android:layout_marginTop="22dp"
android:id="#+id/textView"
android:visibility="visible" />
</RelativeLayout>
The problem is that you have nested fragments and use getFragmentManager(); You should use getChildFragmentManager() instead.
java:
viewPagerAdapter = new PagerAdapter(getChildFragmentManager())
kotlin:
viewPagerAdapter = PagerAdapter(childFragmentManager)
I feel kind of stupid. The problem was with the ViewPager as I suspected. After 3h of code debugging I just moved the ViewPager from the layout with the tabs to another layout which basically connects all of the layouts.
The below sample code is working fine with viewpager and tabs. Try it out.
Main activity layout
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize" />
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
Then viewpager container layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.test.myapplication.MainActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v4.view.ViewPager
android:id="#+id/page_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000" />
</RelativeLayout>
And here is the main activity part:
package com.test.myapplication;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.*;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ViewPager pager = (ViewPager)findViewById(R.id.page_container);
pager.setAdapter(new Adapter(getSupportFragmentManager()));
TabLayout tabs = (TabLayout)findViewById(R.id.tab_container);
tabs.setupWithViewPager(pager, true);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static class Adapter extends FragmentStatePagerAdapter {
private String[] titles = new String[] {"ONE", "TWO"};
public Adapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new com.test.myapplication.Fragment();
case 1:
return new Fragment1();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
If you are using any tablayout with viewpager inside NestedScrollView, make sure to put android:fillViewport="true"
Reference in the nested scrollview. Note that, if you are working with navigation drawer, your fragment may not have a nested scrollview, but your activity fragment container maybe inside a nested scroll view. Because even an empty layout with a background color (for debugging the issue) does not show up, so it was not the problem of view pager in my case, it was the problem with nested scroll view.
Debugging tip: Instead of viewpager, put some layout and set a
background color to see if the layout is visible. If the layout itself
is not visible, then you have issue with the parent layout, most
probably NestedScrollView.
You are missing setupWithViewPager, and you don't need setOnTabSelectedListener:
tab_layout.setupWithViewPager(viewPager)
Let's look here:
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
You have to override also getPageTitle in adapter and there return tab title.
Last, don't use <view ..class> in xml, create normal xml view:
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/view_pager"
android:layout_below="#+id/tab_layout"/>
try this:
in your layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/tab_layout">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:id="#+id/view_pager"
android:layout_below="#+id/tab_layout" />
</RelativeLayout>
in activity:
TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("CASUAL"));
tab_layout.addTab(tab_layout.newTab().setText("RANKED"));
tab_layout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tab_layout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
tab_layout.post(new Runnable() {
#Override
public void run() {
tab_layout.setupWithViewPager(viewPager);
}
});
tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PagerAdapter :
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
// an array of tab titles
private String tabTitles[] = new String[]{"CASUAL", "RANKED"};
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CasualStats tab1 = new CasualStats();
return tab1;
case 1:
RankedStats tab2 = new RankedStats();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
i am new into android programming. I am having difficulty showing a Listview on a ListFragment. I've already tried it on an activity and it worked perfectly, however,i tried displaying the same listview on a Listfragment called from a Navigation Drawer but my app crashes on item click. I have been on it for so long, tried getting answers from different websites but all to no avail.
Pls: A little help would be nice and much appreciated
The error displayed on the logcat is:
09-18 14:35:53.285
3602-3602/com.example.ceede.classwork E/AndroidRuntime: FATAL
EXCEPTION: main Process: com.example.ceede.classwork, PID: 3602
java.lang.NullPointerException at
com.example.ceede.classwork.MainActivity.onNavigationItemSelected(MainActivity.java:92)
at
android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:152)
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.ceede.classwork.MainActivity"
tools:showIn="#layout/app_bar_main">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="android.support.v4.app.ListFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
CustomAdapter.java
package com.example.ceede.classwork;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
CustomAdapter(Context context) {
list = new ArrayList<>();
this.context = context;
Resources res = context.getResources();
String[] titles = res.getStringArray(R.array.Titles);
int[] images = {R.drawable.admisntrationicon, R.drawable.articon, R.drawable.businesseducationicon,
R.drawable.homeicon, R.drawable.drivericon, R.drawable.stafficon,
R.drawable.counciloricon, R.drawable.physicalcon, R.drawable.englishicon,
R.drawable.mathsicon, R.drawable.scienceicon, R.drawable.historyicon,
R.drawable.suporticon};
for (int i = 0; i < titles.length; i++) {
list.add(new SingleRow(titles[i], images[i]));
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
SingleRow temp = list.get(i);
View row = null;
if(view==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.single_row,viewGroup,false);
}
TextView titles= (TextView) row.findViewById(R.id.textAdmin);
ImageView image= (ImageView)row.findViewById(R.id.adminImage);
return row;
}
}
SingleRow.java
class SingleRow {
public String titles;
public int images;
SingleRow(String titles, int images) {
this.titles = titles;
this.images = images;
}
}
MyFragmentClass.java
package com.example.ceede.classwork;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class MyFirstFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_list_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView= (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(new CustomAdapter(getActivity()));
}
public static Fragment newInstance() {
MyFirstFragment frag=new MyFirstFragment();
return frag;
}
}
MainActivity
package com.example.ceede.classwork;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager manager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.contact) {
// Handle the camera action
//Line 92. This is the Line of code causing the error
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.fragment, MyFirstFragment.newInstance());
transaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You should not initialize FragmentManager and call beginTransaction in onCreate. beginTransaction and commit should be paired. If onNavigationItemSelected is called twice you run into trouble when the transaction is already committed.
Better use it this way:
if (id == R.id.contact) {
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
// Handle the camera action
transaction.replace(R.id.fragment, MyFirstFragment.newInstance());
transaction.commit();
}
Try this:
Use
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.my_list_fragment,container,false);
ListView listView= (ListView) view.findViewById(R.id.listView);
listView.setAdapter(new CustomAdapter(getActivity()));
return view;
}
The problems is that your listview is attached to Fragment and not to Activity.
I have a base navigation drawer activity, which will load a fragment. The fragment. The fragment has a recycler view in its layout. The recycler view has an adapter which use Glide to load images from internet. I'm not able to get the image loaded. (Have added the Internet permission in manifest).
My Base activity is:
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Item1Fragment.OnFragmentInteractionListener {
/**
* Frame layout: Which is going to be used as parent layout for child activity layout.
* This layout is protected so that child activity can access this
*/
protected RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
relativeLayout = (RelativeLayout) findViewById(R.id.content_frame);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Add the Very First i.e Squad Fragment to the Container
Fragment item1Fragment = new Item1Fragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_frame, item1Fragment, null);
fragmentTransaction.commit();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_camera) {
Fragment item1Fragment = new Item1Fragment();
fragmentTransaction.replace(R.id.content_frame, item1Fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
Fragment item2Fragment = new Item2Fragment();
fragmentTransaction.replace(R.id.content_frame, item2Fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
Toast.makeText(getApplicationContext(), "333", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_manage) {
Toast.makeText(getApplicationContext(), "444", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_share) {
Toast.makeText(getApplicationContext(), "555", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_send) {
Toast.makeText(getApplicationContext(), "666", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
}
Activity layout is:
<?xml version="1.0" encoding="utf-8"?>
<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" android:background="#color/colorPrimary"
tools:openDrawer="start">
<RelativeLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include
layout="#layout/app_bar_base"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_base"
app:menu="#menu/activity_base_drawer" />
</android.support.v4.widget.DrawerLayout>
Fragment:
import android.content.Context;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Item1Fragment extends Fragment {
private OnFragmentInteractionListener mListener;
private ArrayList<ImageModel> data = new ArrayList<>();
private GalleryAdapter mAdapter;
private RecyclerView mRecyclerView;
public static String IMGS[] = {
"https://images.unsplash.com/photo-1444090542259-0af8fa96557e?q=80&fm=jpg&w=1080&fit=max&s=4b703b77b42e067f949d14581f35019b",
"https://images.unsplash.com/photo-1439546743462-802cabef8e97?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1441155472722-d17942a2b76a?q=80&fm=jpg&w=1080&fit=max&s=80cb5dbcf01265bb81c5e8380e4f5cc1",
"https://images.unsplash.com/photo-1437651025703-2858c944e3eb?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1431538510849-b719825bf08b?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1434873740857-1bc5653afda8?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1439396087961-98bc12c21176?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1433616174899-f847df236857?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1438480478735-3234e63615bb?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1438027316524-6078d503224b?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
for (int i = 0; i < IMGS.length; i++) {
ImageModel imageModel = new ImageModel();
imageModel.setName("Image " + i);
imageModel.setUrl(IMGS[i]);
data.add(imageModel);
}
View view = inflater.inflate(R.layout.fragment_item1,container,false);
mRecyclerView = (RecyclerView)view.findViewById(R.id.list);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}else{
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
}
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(getActivity().getApplicationContext(), data);
mRecyclerView.setAdapter(mAdapter);
return view;
}
//
#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);
}
}
fragment layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.akl.nav2.Item1Fragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/list" android:background="#FFBB00"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
Adapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.ArrayList;
import java.util.List;
/**
* Created by akl on 3/12/2016.
*/
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<ImageModel> data = new ArrayList<>();
public GalleryAdapter(Context context, List<ImageModel> data) {
this.context = context;
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200, 200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
public MyItemHolder(View itemView) {
super(itemView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.akl.nav2">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".BaseActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER"
android:theme="#style/AppTheme.NoActionBar" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
The code was fine. A clean build as suggested by #HoangNguyen was enough to make the code run.
I 'am developing an app that has a gridview with 10 imageButtons.Now i have implemented a method called SquareImageView to adjust the number of columns to 2 irrespective of the screen size.I don't know how to put the texts inside this.
My present application is this:
As you can see there are just images in the grid.I want to give a border,and some text in each of those image in the center bottom.Some thing like this
my files are:
package com.defcomdevs.invento16;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private CollapsingToolbarLayout mcollapsingToolbar;
private NestedScrollView mnestedScrollView;
private CoordinatorLayout coordinatorLayout;
private DrawerLayout drawerLayout;
int backButtonCount = 0;
private Button button;
GridView mygrid;
private ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);
coordinatorLayout.setBackground(getResources().getDrawable(R.drawable.oppo));
// drawerLayout.setBackground(getResources().getDrawable(R.drawable.oppo));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//button= (Button) findViewById(R.id.setalarm);
mcollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
//mnestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
mcollapsingToolbar.setTitle("INVENTO '16");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
callRegister();
}
});
mygrid= (GridView) findViewById(R.id.gridView);
mygrid.setAdapter(new MizAdapter(this));
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void callRegister() {
Intent intent = new Intent(this, Registration.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (backButtonCount >= 1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
/* public void setalarm(View view){
if(view.getId()==R.id.setalarm){
Intent intent=new Intent(this,AlarmActivity.class);
startActivity(intent);
}
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.about_college) {
// Handle the camera action
} else if (id == R.id.cse) {
} else if (id == R.id.it) {
} else if (id == R.id.ece) {
} else if (id == R.id.mech) {
} else if (id == R.id.Coding) {
Intent intent = new Intent(this, Coding.class);
startActivity(intent);
} else if (id == R.id.Hacking) {
} else if (id == R.id.printing) {
} else if (id == R.id.Big) {
} else if (id == R.id.nand) {
} else if (id == R.id.cryo) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class itemName{ //Since we have to bounr the image to the item with the name and the subtitle
//we keep all information inside the class and deal with the class entirely
String Iname;
int ImageId;
itemName(String name,int imageId){
Iname=name;
ImageId=imageId;
}
}
class MizAdapter extends BaseAdapter{
ArrayList<itemName> items;
Context context;
MizAdapter(Context context){
this.context=context;
items=new ArrayList<itemName>(); //initialize each item with the type itemName.
Resources res=context.getResources();
String[] itemnames=res.getStringArray(R.array.Items);
int[] itempics={R.drawable.hackbttn100,R.drawable.hackbttn100,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn};
for(int i=0;i<10;i++){
itemName names=new itemName(itemnames[i],itempics[i]);
items.add(names);
}
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder{
ImageButton myImage;
ViewHolder(View v){
myImage= (ImageButton) v.findViewById(R.id.picture);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
ViewHolder viewHolder=null;
if (row==null){
LayoutInflater inflater= (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.singleitem, parent, false);
viewHolder=new ViewHolder(row);
row.setTag(viewHolder);
}
else {
viewHolder= (ViewHolder) row.getTag();
}
itemName temp=items.get(position);
viewHolder.myImage.setImageResource(temp.ImageId);
return row;
}
public void coding(View v){
}
}
}
Following is to set the numbers of columns to 2 irrespective of screen size.
package com.defcomdevs.invento16;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;
/**
* Created by midhun on 23/10/15.
*/
public class SquareImageView extends ImageButton {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
My mainactivity.xml file
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/app_bar"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="196dp"
android:background="#3f51b5"
app:contentScrim="#color/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/index"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.widget.NestedScrollView>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginTop="198dp"
android:id="#+id/gridView"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:numColumns="2"
android:stretchMode="columnWidth"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
Now each ImageButton has a common layout xml file for it
<?xml version="1.0" encoding="utf-8"?>
<com.defcomdevs.invento16.SquareImageView
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:onClick="coding"
android:background="#drawable/custom_button"/>
Also here i want to define a custom background to all these imagebuttons so that when the user clicks the button a slight transparent color(any color) comes over the image below.
please help me out.
Why not use a separate layout for the grid view layout. So that each button would actually be a layout with a parent layout ie RelativeLayout and Inside the layout you have two child views. One the text view which has a gravity parameter to the bottom. Then the picture as the background of the parent layout.
Use this layout as the Adapters layout. It will recreate it for each item you want.