Hello I am new to android, I am currently trying to navigate from my MainActivity to a TabbedActivity. I created a new TabbedActivity using the default Tabbed Activity template in the Gallery in Android Studio.
However after the files were created, I checked the code and saw that many lines of code used in creating the Activity were cross out, meaning they were deprecated.
I tried running the app, it worked until I tried to navigate to this Tabbed Activity then it crashed and threw an error in my Android Monitor.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxx.eventmanager/com.xxxxxx.eventmanager.EventDetailsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.xxxxxx.eventmanager.EventDetailsActivity.onCreate(EventDetailsActivity.java:42)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is my Tabbed Activity named EventDetailsActivity. I have not added any custom code or made any changes to the default code that was generated on create:
package com.xxxxxx.eventmanager;
import android.app.Activity;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class EventDetailsActivity extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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_event_details, 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);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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 = inflater.inflate(R.layout.fragment_event_details, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
I am new to both Java and Android and quite perplexed by this.
try to change this line
final ActionBar actionBar = getActionBar();
TO
final ActionBar actionBar = getSupportActionBar();
use extends AppCompatActivity and use use the toolbar as..
private void setup_tabs(){
pager = (CustomViewPager)findViewById(R.id.viewpager);
pager.setOffscreenPageLimit(3);
adapter = new Tabs_Pager_adapter(getSupportFragmentManager(),this);
pager.setAdapter(adapter);
pager.setPagingEnabled(true);
// Title.setText(adapter.getPageTitle(pager.getCurrentItem()));
tabLayout = (TabLayout) findViewById(R.id.tabs);
// tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Respondents"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
tabLayout.setupWithViewPager(pager);
}
private void setupToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar != null)
setSupportActionBar(toolbar);
// Show menu icon
final ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowTitleEnabled(false);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
And in your layout..
<LinearLayout
android:layout_weight=".75"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"/>
<your.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And this the theme..
<style name="Base.Theme.your_theme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/my_primary</item>
<item name="colorPrimaryDark">#color/my_primary_dark</item>
<item name="colorAccent">#color/my_accent</item>
</style>
Use the app compat library with android support library... and with design support library.. it is awesome. use the tooolbar layout in your layout.xml
and set the theme with appcompat with no actionbar.
How I treat with toolbar in my app (for example).
In my activity layout xml file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<!-- more xml code below -->
Content of toolbat.xml:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/PopupMenuStyle"
android:background="#color/bar_color">
<!-- arbitrary components are in toolbar -->
</android.support.v7.widget.Toolbar>
Now I prepared for set up the toolbar in my app. In onCreate method I have to use this code before using toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
Since that moment I can use getSupportActionBar() and it will return correct result.
In your case you may use setActionBar(toolbar) instead of setSupportActionBar(toolbar) and <android.widget.Toolbar instead of <android.support.v7.widget.Toolbar in your layout file.
Related
I am getting error while setting up custom views for tabs in tab layout. Every tab runs fine on the first run, but when I swipe between tabs, runtime error appears. I am just trying out tab layout for the first time, can somebody help me with this ?
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.rocks.mafia.entrancesecurity, PID: 18095
android.view.InflateException: Binary XML file line #6: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
at android.view.Choreographer.doCallbacks(Choreographer.java:696)
at android.view.Choreographer.doFrame(Choreographer.java:628)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5740)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
at android.view.Choreographer.doCallbacks(Choreographer.java:696)
at android.view.Choreographer.doFrame(Choreographer.java:628)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5740)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0c009f, tag null, or parent id 0xffffffff with another fragment for com.rocks.mafia.entrancesecurity.HistoryFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2422)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
at android.view.Choreographer.doCallbacks(Choreographer.java:696)
at android.view.Choreographer.doFrame(Choreographer.java:628)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5740)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
MainActivity.java
package com.rocks.mafia.entrancesecurity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
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();
}
});
}
#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_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
switch (id) {
case R.id.action_logout:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.isLogin), false);
editor.commit();
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
View rootView = inflater.inflate(R.layout.history_display, container, false);
return rootView;
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile";
case 1:
return "Requests";
case 2:
return "History";
}
return null;
}
}
}
`
history_display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/historyFrag"
android:name="com.rocks.mafia.entrancesecurity.HistoryFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
fragment_profile.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rocks.mafia.entrancesecurity.ProfileFragment">
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="218dp"
android:background="#color/colorPrimary"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:adjustViewBounds="true"
android:src="#drawable/ln_logo"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:minHeight="?android:attr/actionBarSize"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_profile" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_star_black"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
fragment_main.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"
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="com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
The answer is simple : don't use xml fragments at all. It is bad supported, has a lot of limitations, like that with which you met. The problem is that two same xml fragments ( without workarounds) couldn't exist together, because them share same fragment id. The crash happends when history fragment tried to recreate it's view, due to page changing process, but previous one still hadn't been garbage collected.
Sure, you still could setOffscreenPageLimit on ViewPager to 2 in your case ( all views will stay in memory) , but you should just remove you xml fragment and attach it programmatically if really needed.
What I have been Trying to Do
What I have been aiming to do for several days is, using an Activity that implements NavigationView.OnNavigationItemSelectedListener. I want this to create two Tabs inside a android.support.v4.app.Fragment in the FrameLayout provided by the template for the Navigation Drawer on Android Studio 1.5.1.
- My Current Activity uses a toolbar not an ActionBar.
- I was hoping to use a ViewPager; hence needing to use Support Fragments.
- I have followed several code examples online and have looked at Android Developers Reference.
Other Linked Posts:
Unable to add Tabs inside Fragment of Navigation Drawer Android | This uses Fragments and the ActionBar
Android TabHost inside Fragment | Chosen Answer -> using FragmentActivity | Unfortunatly uses a new FragmentActivity but I need to keep my NavigationDrawer so am using one activity
Android TabHost only inside one Fragment (NavigationDrawer) | This didnt really provide me much help as I am very new to using tabs
Android Adding Tab inside Fragment | Chosen Answer -> using FragmentTabHost | I have taken FragmentTabHost XML and Java code from this example but It has not worked
Tabs in a class that extends fragment | The andswer refers to googles documentation which is not working for me.
Adding Tab inside Fragment In Android? | Uses android.app.Fragment and the suggested answer didnt work.
Using TabLayout inside a Fragment; tab text invisible | I am using Design Library v23.1.1 | Bugs reported in v22.2.1. The code here gave me no tabs either
Any Suggestion would be appreciated.
MY CODE
NavActivity Class
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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;
public class NavigationMenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navmenu_act);
//Setting up the Toolbar
toolbar = (Toolbar) findViewById(R.id.navmenu_appbar_tbar);
setSupportActionBar(toolbar);
//Set up the action bar toggle
drawerLayout = (DrawerLayout) findViewById(R.id.navmenu_act_drawerlay);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
//Set up the navigation View
navigationView = (NavigationView) findViewById(R.id.navmenu_nav_view);
navigationView.setNavigationItemSelectedListener(this);
//SET THE FRAGMENT
fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.navmenu_appbar_fl);
if(fragment==null) { //If no fragment exists relate the fragment
fragment = new TabLayoutFragmentExample();
fragmentManager.beginTransaction()
.add(R.id.navmenu_appbar_fl, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.navmenu_act_drawerlay);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.navmenu_appbar_fl);
if(fragment!=null) { //If a fragment exists replace the fragment
fragment = new TestFragmentNoTabs();
fragmentManager.beginTransaction()
.replace(R.id.navmenu_appbar_fl, fragment)
.commit();
}
} else if (id == R.id.nav_near_me) {
// Handle the near me action here
} else if (id == R.id.nav_proximity) {
// Handle the proximity action
fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.navmenu_appbar_fl);
if(fragment!=null) {//If A fragment exists replace the fragment
fragment = new TestFragmentNoTabsTWO();
fragmentManager.beginTransaction()
.replace(R.id.navmenu_appbar_fl, fragment)
.commit();
}
}
//Close the drawerLayout after it is clicked?
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.navmenu_act_drawerlay);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//sync the toggle
toggle.syncState();
}
}
navmenu_appbar.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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".NavigationMenuActivity">
<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/navmenu_appbar_tbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/JethrosTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/navmenu_appbar_fl"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</android.support.design.widget.CoordinatorLayout>
TablayoutFragmentExample Class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class TabLayoutFragmentExample extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.tab_layout_frag, container, false);
TabLayout tabLayout = (TabLayout) inflatedView.findViewById(R.id.tab_layout_frag_tl);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
final ViewPager viewPager = (ViewPager) inflatedView.findViewById(R.id.tab_layout_frag_vp);
viewPager.setAdapter(new PagerAdapter //ChildFragManager; Tnx #Luksprog
(getChildFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager); //Set Viewpager; Tnx #Luksprog
return inflatedView;
}
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:
TestFragmentNoTabs tab1 = new TestFragmentNoTabs();
return tab1;
case 1:
TestFragmentNoTabsTWO tab2 = new TestFragmentNoTabsTWO();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
tab_layout_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout_frag_tl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/tab_layout_frag_vp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
</android.support.design.widget.AppBarLayout>
TestFragmentNoTabs & TestFragmentNoTabsTWO (Fragment 1 and fragment 2)
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public class TestFragmentNoTabs extends Fragment {
public final String TAG = "TestFragmentNoTabs";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the fragment view
View view = inflater.inflate(R.layout.testfragnotabs, container, false);
return view; //Return the view to the activity
}
#Override
public void onPause() {
super.onPause();
}
}
testfragnotabs.xml (similar to testfragnotabstwo.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nearme_frag_rlay"
android:clickable="false">
<TextView
android:id="#+id/nearme_frag_tv_seclab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" TestFragmentNoTabsOne -> testfragnotabs.xml" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView1"
android:layout_above="#+id/nearme_frag_tv_seclab" />
</RelativeLayout>
Current Situation with Above Code
The project builds fine and the navigation drawer is working fine as well. However the frame layout where the fragment and the TabLayout should appear is empty with a white background (Just like the Design preview in tab_layout_frag.xml; this could mean there is a problem with the ViewPager or the TabLayout?).
Here is main activity layout XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/left"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
<android.support.v4.view.ViewPager
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_toLeftOf="#+id/left"
android:layout_toRightOf="#+id/right"
tools:context=".MainActivity" />
<LinearLayout
android:id="#+id/right"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
Fragment Layout 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:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="horizontal"
tools:context=".DummySectionFragment" android:background="#color/gray">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Main Activity :
package com.example.androidtest;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager(), getApplicationContext());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
}
Fragment :
package com.example.androidtest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
Pager Adapter :
package com.example.androidtest;
import java.util.Locale;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return context.getString(R.string.title_section1).toUpperCase(l);
case 1:
return context.getString(R.string.title_section2).toUpperCase(l);
case 2:
return context.getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Expected : 2 red bars on both sides. ViewPager in the middle.
Whats happening : 2 red bars on both sides. Blank in the middle.
Question : Why ?
EDIT :
I modified the main activity layout XML to the following to get this to work.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/left"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
<android.support.v4.view.ViewPager
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" android:layout_toRightOf="#+id/left"/>
<LinearLayout
android:id="#+id/right"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
Only change is I removed android:layout_toRightOf="#+id/right" and changed layout_width="fill_parent". Fill_parent I understand. By why does removing the other make a difference ?
You have to do two things in main.xml:
Use LinearLayout instead of RelativeLayout for your main.xml with horizontal orientation.
Add android:layout_weight="1" to your View Pager.
Well, your viewPager's width is: android:layout_width="0dip". No wonder is blank in the middle. Try setting it to android:layout_width="match_parent". In this way it will use all space between right and left views.
I have 4 views, two of which contain mapviews. What I really want in the end is a tabbed navigation between these 4 views.
After some research, it seams like the best idea would be to use ActionBarSherlock and make each one of these views a "Fragment" inside a master "Main" Activity. This seams like a very easy to do thing but is causing me massive amounts of trouble (indeed, seams to be a pain for everyone from what I can find online).
First, my code.
ActivityMain.java
public class ActivityMain extends SherlockFragmentActivity
{
static String CLASS_NAME = "ActivityMain";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.v(CLASS_NAME, "here");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.createMenu();
}
public void createMenu()
{
this.getSupportActionBar().setDisplayShowHomeEnabled(false);
this.getSupportActionBar().setDisplayShowTitleEnabled(false);
this.getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab1 = getSupportActionBar()
.newTab()
.setText("First tab")
.setTabListener(new MyTabListener<FragmentOne>(this, FragmentOne.class));
getSupportActionBar().addTab(tab1);
Tab tab2 = getSupportActionBar()
.newTab()
.setText("Second tab")
.setTabListener(new MyTabListener<FragmentTwo>(this, FragmentTwo.class));
getSupportActionBar().addTab(tab2);
}
public class MyTabListener<T extends Fragment> implements TabListener
{
private ActivityMain mActivity;
private Fragment mFragment;
private Class<T> mClass;
public MyTabListener(ActivityMain activity, Class<T> fragmentClass)
{
mActivity = activity;
mClass = fragmentClass;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
if (mFragment == null)
{
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, null);
}
else
{
//ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.animationtest);
ft.attach(mFragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
if (mFragment != null)
{
ft.detach(mFragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
}
}
FragmentOne loads just fine, no problems on that one. FragmentTwo is where the trouble begins. Here is the files:
FragmentTwo.java
package com.test;
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends SherlockFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.v("Test", "Two!");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.two, container, false);
return view;
}
}
and the corresponding layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapMapView"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="0.40"
android:clickable="true"
android:apiKey="MY_KEY"
/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
style="#android:style/ButtonBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/refreshButton"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:onClick="refreshSightings"
android:text="#string/A_MAP_REFRESH_BUTTON" />
</LinearLayout>
</LinearLayout>
Now of course this is giving me the error Binary XML file line #7: Error inflating class com.google.android.maps.MapView
I have tried importing the https://github.com/petedoyle/android-support-v4-googlemaps package and replacing the already existing android-support-v4 package but when I try to run my app, it dies with the error that it can't find the ActivityMain class.
First question, am I even going about this in the right way? Should I be using this 1 main activity and loading all the other things in Fragments?
Next, if I am doing this in a correct way, is there a good tutorial for how to get this to work in a decent way? I can't find anything online except for other people asking the same questions and a few tutorials that haven't worked for me.
Basically, how can I have tabbed navigation with 2 maps in 2 different tabs?
I am trying to make a very simple App, but there's an error I can't get rid of it. Maybe someone can help me.
I'm making an Activity with an ActionBar and 3 Tabs. Beneath the Tabs is a FrameLayout, where I put Fragments with a TextView in it. So when clicking on a tab the content of the TextView shoud change.
This works fine until I change the orientation. After the change there is a duplicate TextView and I have no idea where it cames from. Here's a picture for better understanding:
Overlapping TextViews
Here's my Activity:
package com.test;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.os.Bundle;
import android.widget.Toast;
public class ProblemActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String tab1 = "First Tab";
bar.addTab(bar
.newTab()
.setText(tab1)
.setTabListener(
new TabListener(new First())));
String tab2 = "Second Tab";
bar.addTab(bar
.newTab()
.setText(tab2)
.setTabListener(
new TabListener(new Second())));
String tab3 = "Third Tab";
bar.addTab(bar
.newTab()
.setText(tab3)
.setTabListener(
new TabListener(new Third())));
}
private class TabListener implements ActionBar.TabListener {
private MyFragment mFragment;
public TabListener(MyFragment fragment) {
this.mFragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_content, mFragment, null);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(mFragment);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(ProblemActivity.this, "Reselected!", Toast.LENGTH_SHORT)
.show();
}
}
}
The Fragment's:
public class First extends MyFragment {
public First() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragView = inflater.inflate(R.layout.tab1, container, false);
TextView tv = (TextView) fragView.findViewById(R.id.textView1);
tv.setText("First Tab");
return fragView;
}
}
main.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="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
and the content of the Fragment's.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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="TextView"
android:textSize="35dp" />
</LinearLayout>
It would be amazing if some could show me what I'm making wrong.
Thank's in advance!
Edit: I tried already this proposed solution but I would like to work with class Objects, so that I can use their Methods.
Edit2: Solved the problem now. It was sufficient to add android:configChanges="keyboardHidden|orientation|screenSize" to my Activity.
Since the OP already solved his problem, but hasn't been active on SO for almost a year, here is an answer containing the solution:
Adding the following to the Activity solved the problem:
android:configChanges="keyboardHidden|orientation|screenSize"
You can get overlapping views if there is something wrong with one of your layouts. This seems to happen in particular if you have a fragment. For example, a View in the Fragment can overlap a View in the containing layout.
Sometimes this can be fixed by Cleaning your project (if you are using Eclipse).