Android create fragment more than one time - android

Using this sample: I have make my own Fragment that holds tabhost and tab content:
public class TabsFragment extends Fragment
{
private static final String EXTRA_TAB = "EXTRA_TAB";
private TabHost tabHost;
private TabManager tabManager;
private MaptrixFragmentActivity activity;
private Context context;
#Override
public void onAttach(Activity activity)
{
this.activity = (MaptrixFragmentActivity) activity;
this.context = activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_tabs, container, false);
tabHost = (TabHost)view.findViewById(android.R.id.tabhost);
tabHost.setup();
tabManager = new TabManager(activity, tabHost, R.id.realtabcontent);
initTabs();
if (savedInstanceState != null)
{
tabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB));
}
return view;
}
private void initTabs()
{
// tab one
addTab(Fragment.class, null, R.drawable.icon1, Res.S(R.string.tab1));
// I have not implement the tab fragment yet!
// tab two
addTab(Fragment.class, null, R.drawable.icon2, Res.S(R.string.tab2));
}
private void addTab(Class<?> fragmenClass, Bundle bundle, int drawableId, String tag)
{
TabHost.TabSpec spec = tabHost.newTabSpec(tag);
View tabIndicator = LayoutInflater.from(context).inflate(R.layout.item_tab, tabHost.getTabWidget(), false);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.tab_image);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
tabManager.addTab(spec, fragmenClass, bundle);
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putString(EXTRA_TAB, tabHost.getCurrentTabTag());
}
public static class TabManager implements TabHost.OnTabChangeListener
{
private final FragmentActivity activity;
private final TabHost tabHost;
private final int containerID;
private final HashMap<String, TabInfo> tabs = new HashMap<String, TabInfo>();
TabInfo lastTab;
TabFactory factory;
public TabManager(FragmentActivity activity, TabHost tabHost, int containerID)
{
this.activity = activity;
this.tabHost = tabHost;
this.containerID = containerID;
factory = new TabFactory(activity);
tabHost.setOnTabChangedListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)
{
tabSpec.setContent(factory);
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
info.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
if (info.fragment != null && !info.fragment.isDetached())
{
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.detach(info.fragment);
ft.commit();
}
tabs.put(tag, info);
tabHost.addTab(tabSpec);
}
#Override
public void onTabChanged(String tabId)
{
TabInfo newTab = tabs.get(tabId);
if (lastTab != newTab)
{
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
if (lastTab != null) {
if (lastTab.fragment != null)
{
ft.detach(lastTab.fragment);
}
}
if (newTab != null)
{
if (newTab.fragment == null)
{
newTab.fragment = Fragment.instantiate(activity, newTab.clss.getName(), newTab.args);
ft.add(containerID, newTab.fragment, newTab.tag);
}
else
{
ft.attach(newTab.fragment);
}
}
lastTab = newTab;
ft.commit();
}
}
}
private static class TabInfo
{
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;
TabInfo(String _tag, Class<?> _class, Bundle _args)
{
tag = _tag;
clss = _class;
args = _args;
}
}
private static class TabFactory implements TabHost.TabContentFactory
{
private final Context mContext;
public TabFactory(Context context)
{
mContext = context;
}
#Override
public View createTabContent(String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
}
But onCreateView method calls two or more times when device changes orientation.
My FragmentActivity is:
public class MaptrixFragmentActivity extends FragmentActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.factivity);
replace(R.id.factivity_content, new TabsFragment(), false, false);
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
public void replace(int rootView, Fragment fragment)
{
replace(rootView, fragment, true, true);
}
public void replace(int rootView, Fragment fragment, boolean backStack)
{
replace(rootView, fragment, backStack, true);
}
public void replace(int rootView, Fragment fragment, boolean backStack, boolean animation)
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (animation) transaction.setCustomAnimations(R.anim.fragment_open, R.anim.fragment_close, R.anim.fragment_open_stack, R.anim.fragment_close_stack);
if (backStack) transaction.addToBackStack(null);
transaction.replace(R.id.factivity_maptrix_content, fragment);
transaction.commit();
}
}
Why i have this bug?

You could perhaps add android:configChanges="keyboardHidden|orientation" to your AndroidManifest.xml file. This avoids recreating the activity when orientation changes and therefore the TabsFragment won't be created twice.
<activity android:name="MaptrixFragmentActivity" android:configChanges="keyboardHidden|orientation">
See this for more details.

Related

Android set icon to customTabHost

i'm wrote simple code to have custom TabHost in application. this class extended from ABS and fregment, this code work correctly and i want to set icon for tabs, but i can not do it.
public class ActivitySmsSendSelectorMain extends SherlockFragmentActivity {
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_send_selector_main);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
mTabsAdapter.addTab(mTabHost.newTabSpec("ContactView")
.setIndicator(UC.getResourcesText(R.string.abs_sms_send_selector_contact_view)),
FragmentSample1.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("MobileArchive")
.setIndicator(UC.getResourcesText(R.string.abs_sms_send_selector_archive_mobile)),
FragmentSample2.class, null);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final String tag;
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
i'm try to change mTabHost to :
mTabsAdapter.addTab(mTabHost.newTabSpec("ContactView")
.setIndicator(UC.getResourcesText(R.string.abs_sms_send_selector_contact_view),
G.context.getResources().getDrawable(R.drawable.app_user)),
FragmentSmsSendSelectorContactView.class, null);
but it doesnt show icon into tab

Get Fragment Text View from Activity

So Im using view pager and action bar to set fragments in my activity, now I want to set text on one of my fragment from the container activity which at the moment seems impossible to me..Googling suggested that Fragment.bgintransaction() should be added with the tag and then should be identified with that tag but here in my pager based fragment there is no BeginTransaction() method. Kindly suggest any way of doin
public class AdminTabsPager extends SherlockFragmentActivity {
private TabHost mTabHost;
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private String comingFrom ="";
private String moduleName ="";
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
return;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
Bundle bundle = this.getIntent().getExtras();
if(bundle.containsKey("name")) {
comingFrom = bundle.getString("name");
}
if(bundle.containsKey("module")) {
moduleName = bundle.getString("module");
}
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(1);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
mTabsAdapter.addTab(mTabHost.newTabSpec("Tab 1").setIndicator("Tab 1"),TabOneFragmentActivity.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("Tab 2").setIndicator("Tab 2"),TabTwoFragmentActivity.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("Tab 3").setIndicator("Tab 3"),TabThreeFragmentActivity.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("Tab 4").setIndicator("Tab 4"),TabFoureFragmentActivity.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("Tab 5").setIndicator("Tab 5"),TabFiveFragmentActivity.class, null);
if(bundle.containsKey("name") && comingFrom.equals("Tab_1Fragment")) {
mTabHost.setCurrentTab(3);
}else if(bundle.containsKey("name") && comingFrom.equals("Tab_2Fragment")) {
mTabHost.setCurrentTab(4);
}else if(bundle.containsKey("name") && comingFrom.equals("Tab_3Fragment")) {
mTabHost.setCurrentTab(0);
}else if(bundle.containsKey("name") && comingFrom.equals("Tab_4Fragment")) {
mTabHost.setCurrentTab(1);
}else {
mTabHost.setCurrentTab(0);
}
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
widget.setDescendantFocusability(oldFocusability);
mTabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
}

Fragmentation Tab open By Default 3rd tab

I have Create Fragment Tab where 6 Tab are available when we call this tab then it open by default first tab but we want to implement when we call this page then its by default open 3rd tab how bto resolve it please suggest.
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
tabHost = FindViewById<TabHost>(Android.Resource.Id.TabHost);
tabHost.Setup();
viewPager = FindViewById<ViewPager>(Resource.Id.pager);
tabsAdapter = new TabsAdapter(this, tabHost, viewPager);
tabsAdapter.AddTab(tabHost.NewTabSpec("Sale").SetIndicator("Sale"), Java.Lang.Class.FromType(typeof(retailerStockSaleList.PageFragment)), null);
tabsAdapter.AddTab(tabHost.NewTabSpec("L Y S M Sale").SetIndicator("L Y S M Sale"), Java.Lang.Class.FromType(typeof(retailerStockSale1List.PageFragment)), null);
tabsAdapter.AddTab(tabHost.NewTabSpec("L M Sale").SetIndicator("L M Sale"), Java.Lang.Class.FromType(typeof(retailerStockSaleLMList.PageFragment)), null);
tabsAdapter.AddTab(tabHost.NewTabSpec("Stock").SetIndicator("Stock"), Java.Lang.Class.FromType(typeof(retailerPhysicalStockList.PageFragment)), null);
tabsAdapter.AddTab(tabHost.NewTabSpec("Order List").SetIndicator("Order List"), Java.Lang.Class.FromType(typeof(retailerOrderList.PageFragment)), null);
tabsAdapter.AddTab(tabHost.NewTabSpec("Retailer Details").SetIndicator("Retailer Details"), Java.Lang.Class.FromType(typeof(retailerDetail.PageFragment)), null);
if (bundle != null)
{
tabHost.SetCurrentTabByTag(bundle.GetString("tab"));
}
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
outState.PutString("tab", tabHost.CurrentTabTag);
}
protected class TabsAdapter : FragmentPagerAdapter, TabHost.IOnTabChangeListener, ViewPager.IOnPageChangeListener
{
private Context _context;
private TabHost _tabHost;
private ViewPager _viewPager;
private List<TabInfo> _tabs = new List<TabInfo>();
public class TabInfo
{
public string tag;
public Class clss;
public Bundle args;
public Android.Support.V4.App.Fragment fragment { get; set; }
public TabInfo(string _tag, Class _class, Bundle _args)
{
tag = _tag;
clss = _class;
args = _args;
}
}
public class DummyTabFactory : Java.Lang.Object, TabHost.ITabContentFactory
{
private Context _context;
public DummyTabFactory(Context context)
{
_context = context;
}
public View CreateTabContent(string tag)
{
var v = new View(_context);
v.SetMinimumHeight(0);
v.SetMinimumWidth(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager)
: base(activity.SupportFragmentManager)
{
_context = activity;
_tabHost = tabHost;
_viewPager = pager;
_tabHost.SetOnTabChangedListener(this);
_viewPager.Adapter = this;
_viewPager.SetOnPageChangeListener(this);
}
public void AddTab(TabHost.TabSpec tabSpec, Class clss, Bundle args)
{
tabSpec.SetContent(new DummyTabFactory(_context));
var tag = tabSpec.Tag;
var info = new TabInfo(tag, clss, args);
_tabs.Add(info);
_tabHost.AddTab(tabSpec);
NotifyDataSetChanged();
}
public override int Count
{
get
{
return _tabs.Count;
}
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
var info = _tabs[position];
return Android.Support.V4.App.Fragment.Instantiate(_context, info.clss.Name, info.args);
}
public void OnTabChanged(string tabId)
{
int position ;
position = _tabHost.CurrentTab;
_viewPager.CurrentItem = position;
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void OnPageSelected(int position)
{
var widget = _tabHost.TabWidget;
var oldFocusability = widget.DescendantFocusability;
widget.DescendantFocusability = DescendantFocusability.BlockDescendants;
_tabHost.CurrentTab = position;
widget.DescendantFocusability = oldFocusability;
}
}
}
}

Fragment cannot be cast to an android.app.activity

I created a very fragment to test my app and I got the following error message:
03-28 11:11:58.079: E/AndroidRuntime(11760):
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.android.demoresponsevision/com.android.demoresponsevision.fragment.BarcodeScreen}:
java.lang.ClassCastException:
com.android.demoresponsevision.fragment.BarcodeScreen cannot be cast
to android.app.Activity
Fragment Code:-
public class BarcodeScreen extends Fragment {
TextView tvStatus;
TextView tvResult;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.barcode, container, false);
tvStatus = (TextView) view.findViewById(R.id.tvStatus);
tvResult = (TextView) view.findViewById(R.id.tvResult);
Button scanBtn = (Button) view.findViewById(R.id.btnScan);
// in some trigger function e.g. button press within your code you
// should add:
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Utilites.showToast(getActivity(), "Try");
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), "ERROR:" + e, 1).show();
}
}
});
return view;
}
// In the same activity you’ll need the following to retrieve the results:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
Toast.makeText(getActivity(), "result ", 1000).show();
if (requestCode == 0) {
if (resultCode == getActivity().RESULT_OK) {
tvStatus.setText(intent.getStringExtra("SCAN_RESULT_FORMAT"));
tvResult.setText(intent.getStringExtra("SCAN_RESULT"));
}
else if (resultCode == getActivity().RESULT_CANCELED) {
tvStatus.setText("Press a button to start a scan.");
tvResult.setText("Scan cancelled.");
}
}
}
}
This is my Fragment Activity
public class TabActivity extends FragmentActivity implements
OnTabChangeListener {
TextView txt;
private TabHost mTabHost;
private HashMap mapTabInfo = new HashMap();
private TabInfo mLastTab = null;
private class TabInfo {
private String tag;
private Class clss;
private Bundle args;
private Fragment fragment;
TabInfo(String tag, Class clazz, Bundle args) {
this.tag = tag;
this.clss = clazz;
this.args = args;
}
}
class TabFactory implements TabContentFactory {
private final Context mContext;
/** * #param context */
public TabFactory(Context context) {
mContext = context;
}
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
// Step 2: Setup TabHost
initialiseTabHost(savedInstanceState);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
protected void onSaveInstanceState(Bundle outState) {
outState.putString("tab", mTabHost.getCurrentTabTag()); // save the tab
// selected
super.onSaveInstanceState(outState);
}
/**
* Step 2: Setup TabHost
*/
private void initialiseTabHost(Bundle args) {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
TabInfo tabInfo = null;
TabActivity.addTab(this, this.mTabHost, this.mTabHost
.newTabSpec("Tab1").setIndicator("HomeScreen"),
(tabInfo = new TabInfo("Tab1", HomeScreen.class, args)));
this.mapTabInfo.put(tabInfo.tag, tabInfo);
TabActivity.addTab(this, this.mTabHost, this.mTabHost
.newTabSpec("Tab2").setIndicator("SecondScreen"),
(tabInfo = new TabInfo("Tab2", SecondHomeScreen.class, args)));
this.mapTabInfo.put(tabInfo.tag, tabInfo);
// Default to first tab
this.onTabChanged("Tab1");
//
mTabHost.setOnTabChangedListener((OnTabChangeListener) this);
}
private static void addTab(TabActivity activity, TabHost tabHost,
TabHost.TabSpec tabSpec, TabInfo tabInfo) { // Attach a Tab view
// factory to the spec
tabSpec.setContent(activity.new TabFactory(activity));
String tag = tabSpec.getTag();
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
tabInfo.fragment = activity.getSupportFragmentManager()
.findFragmentByTag(tag);
if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
FragmentTransaction ft = activity.getSupportFragmentManager()
.beginTransaction();
ft.detach(tabInfo.fragment);
ft.commit();
activity.getSupportFragmentManager().executePendingTransactions();
}
tabHost.addTab(tabSpec);
}
/**
* (non-Javadoc) * #see
* android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
*/
public void onTabChanged(String tag) {
TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag);
if (mLastTab != newTab) {
FragmentTransaction ft = this.getSupportFragmentManager()
.beginTransaction();
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(this,
newTab.clss.getName(), newTab.args);
ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
ft.commit();
this.getSupportFragmentManager().executePendingTransactions();
}
}
}
HomeScreen :-
public class HomeScreen extends Fragment implements OnItemClickListener {
ListView list;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
list = (ListView) view.findViewById(R.id.list);
String[] values = new String[] { "Barcode scanner", "Photos ", "Map",
"Signature" };
ArrayAdapter<String> files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
list.setAdapter(files);
list.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if (position == 0) {
Utilites.showToast(getActivity(), "Barcode");
Intent i_barcode = new Intent(getActivity(), BarcodeScreen.class);
startActivity(i_barcode);
}
if (position == 1) {
Utilites.showToast(getActivity(), "Photos");
Intent i_photo = new Intent(getActivity(), PhotoScreen.class);
startActivity(i_photo);
}
if (position == 2) {
Utilites.showToast(getActivity(), "Map");
Intent i_map = new Intent(getActivity(), MapScreen.class);
startActivity(i_map);
}
if (position == 3) {
Utilites.showToast(getActivity(), "Signature");
Intent i_signature = new Intent(getActivity(), BarcodeScreen.class);
startActivity(i_signature);
}
}
}
Unable to instantiate activity
ComponentInfo{com.android.demoresponsevision/com.android.demoresponsevision.fragment.BarcodeScreen}:
java.lang.ClassCastException:
com.android.demoresponsevision.fragment.BarcodeScreen cannot be cast
to android.app.Activity
This stakctrace clearly indicates that BarcodeScreen is not a Activity.
You are using startActivity for fragments some where in your code.
Problem confirmed by below code
Intent i_barcode = new Intent(getActivity(), BarcodeScreen.class);
startActivity(i_barcode);
And you also said you made an entry of BarcodeScreen in manifest. Fragment is not a Activity. So what you are doing is wrong.
You need to have a container which is a ViewGroup and add or replace fragments to it.
Read
http://developer.android.com/guide/components/fragments.html

Android: Locking screen orientation on a single tab

I have a TabHost with five tabs, we'll call it tab 1-5.
I would like Tab 3 to stay portrait - I don't want it to ever go landscape.
How would I achieve this?
Here is my current code (Main.class):
public class Main extends FragmentActivity {
TabHost mTabHost;
TabManager mTabManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
addTab(mTabManager, mTabHost, new String("Tab 1"), new String("tab1"),
Tab1.class);
addTab(mTabManager, mTabHost, new String("Tab 2"), new String("tab2"),
Tab2.class);
addTab(mTabManager, mTabHost, new String("Tab 3"), new String("tab3"),
Tab3.class);
addTab(mTabManager, mTabHost, new String("Tab 4"), new String("tab4"),
Tab4.class);
addTab(mTabManager, mTabHost, new String("Contact"), new String("contact"),
Tab5.class);
mTabHost.getTabWidget().getChildTabViewAt(0).setFocusable(false);
mTabHost.getTabWidget().getChildTabViewAt(1).setFocusable(false);
mTabHost.getTabWidget().getChildTabViewAt(2).setFocusable(false);
mTabHost.getTabWidget().getChildTabViewAt(3).setFocusable(false);
mTabHost.getTabWidget().getChildTabViewAt(4).setFocusable(false);
mTabHost.setSelected(false);
mTabHost.getTabWidget().setSelected(false);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
private static View prepareTabView(Context context, String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_bg, null);
((TextView) view.findViewById(R.id.tabsText)).setText(text);
return view;
}
public static void addTab(TabManager manager, TabHost host, String title, String tag, Class<?> cl) {
TabHost.TabSpec spec = host.newTabSpec(tag);
View view = prepareTabView(host.getContext(), title);
spec.setIndicator(view);
manager.addTab(spec, cl, null);
}
public static class TabManager implements TabHost.OnTabChangeListener {
private final FragmentActivity mActivity;
private final TabHost mTabHost;
private final int mContainerId;
private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
TabInfo mLastTab;
static final class TabInfo {
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
mActivity = activity;
mTabHost = tabHost;
mContainerId = containerId;
mTabHost.setOnTabChangedListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mActivity));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
if (info.fragment != null && !info.fragment.isDetached()) {
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
ft.detach(info.fragment);
ft.commit();
}
mTabs.put(tag, info);
mTabHost.addTab(tabSpec);
}
#Override
public void onTabChanged(String tabId) {
TabInfo newTab = mTabs.get(tabId);
if (mLastTab != newTab) {
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mActivity,
newTab.clss.getName(), newTab.args);
ft.add(mContainerId, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
ft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
}
}
I'm assuming from your AndroidManiest.xml file that each of your tabs are activities.
If so, then take a look at Activity.setRequestedOrientation(int)
In your Tab3 Activity class you can lock your activity in to portrait mode using the following code :
public class Tab3 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
In all your other Tab activities you can turn ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR on.
the easiest way is you go to the manifest.XML
in any activity you want it in portrait add this line in bold
android:screenOrientation="portrait"
In your case:
<activity
android:name=".Main"
android:screenOrientation="portrait" />

Categories

Resources