Android FragmentTabHost access fragment's view from actionbar activity's OnOptionsItemSelected - android

I am new to android development. I am trying to use Fragmenttabhost in my project.
In My project I have three tabs.Each tab has three EditTextview.
I want to access all three tab's editText value in MainActivity's OnOptionsItemSelected event.
fragmentTab.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost 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="match_parent"
android:orientation="vertical">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</HorizontalScrollView>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
MainActivity
public class FragmentTabs extends ActionBarActivity{
private FragmentTabHost mTabHost;
FragmentTab1 fragmentTab1;
FragmentTab2 fragmentTab2;
FragmentTab3 fragmentTab3;
EditText tab1_ediTxt1,tab1_ediTxt2,tab1_ediTxt3;
EditText tab2_ediTxt1,tab2_ediTxt2,tab2_ediTxt3;
EditText tab3_ediTxt1,tab3_ediTxt2,tab3_ediTxt3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("Simple1"),
FragmentTab1.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("Simple2"),
FragmentTab2.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab3").setIndicator("Simple3"),
FragmentTab3.class, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_save:
{
fragmentTab1=(FragmentTab1)SupportFragmentManager.FindFragmentByTag("Tab1");
fragmentTab2=(FragmentTab1)SupportFragmentManager.FindFragmentByTag("Tab2");
fragmentTab3=(FragmentTab1)SupportFragmentManager.FindFragmentByTag("Tab3");
getTab1view();
getTab2view();
getTab3view();
}
}
public void getTab1view()
{
tab1_ediTxt1= (EditText)fragmentTab1.View.FindViewById(R.id.tab1_edittext1);
tab1_ediTxt2= (EditText)fragmentTab1.View.FindViewById(R.id.tab1_edittext2);
tab1_ediTxt3= (EditText)fragmentTab1.View.FindViewById(R.id.tab1_edittext3);
}
public void getTab2view()
{
tab2_ediTxt1== (EditText)fragmentTab2.View.FindViewById(R.id.tab2_edittext1);
tab2_ediTxt2== (EditText)fragmentTab2.View.FindViewById(R.id.tab2_edittext2);
tab2_ediTxt3== (EditText)fragmentTab2.View.FindViewById(R.id.tab2_edittext3);
}
public void getTab3view()
{
tab3_ediTxt1= (EditText)fragmentTab3.View.FindViewById(R.id.tab3_edittext1);
tab3_ediTxt2= (EditText)fragmentTab3.View.FindViewById(R.id.tab3_edittext2);
tab3_ediTxt3= (EditText)fragmentTab3.View.FindViewById(R.id.tab3_edittext3);
}
}
FragmentTab1
public class FragmentTab1 extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container,false);
Editext editTxt1 = (Editext) v.findViewById(R.id.tab1_edittext1);
Editext editTxt2 = (Editext) v.findViewById(R.id.tab1_edittext2);
Editext editTxt3 = (Editext) v.findViewById(R.id.tab1_edittext3);
return v;
}
}
FragmentTab2,FragmentTab3 as same as FragmentTab1.
I have access the current selected tab's editText value.
(For Example) suppose 1st tab is currently selected means I can access all edittext values from the tab but remaining 2nd and 3rd tab editText returns null.
I can only access visibile tabs view by using FindFragmentbyTag.
But unable to access unselected/unvisible tabs view
Can any one please help me to acces all three tab's editetxt value access form MainActivity onOptionsItemSelected event.

Related

Laggy switching between fragments using a drawerlayout - android

I'm encountering slow/laggy behaviour when swithcing between frgaments using a drawerlayout. I've read up here on stackoverflow and elsewhere regarding solving this issue and a major piece of advice e.g. as seen here is to populating bits of fragment related views elsewhere hence my question of how best can one do the populating part outside of onCreateView() to avoid the laggy behaviour.
Any help is appreciated.
My code is as follows:
My main activity below:
/*! Main activity class */
public class MainActivity extends ActionBarActivity implements FragListener {
/** Private vars */
private DrawerLayout drawerLayout;
private ListView lvDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private CharSequence drawerTitle;
private CharSequence title;
private DrawerLayoutAdapter drawerLayoutAdapter;
private List<DrawerLayoutDrawer> lvDrawerLayoutData;
/** Public vars */
public static String TAG = "MainActivity";
public MainActivity mainActivity;
public Display display;
public Typeface officialBoldFont, officialRegularFont;
public TextView actionBarTView, tvActionBarTitle = null;
public Fragment fragment;
//!<
public MainActivity() {
}
//!<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getTitle() is part of Activity
title = drawerTitle = getTitle();
// Obtain the normal device display area
display = getWindowManager().getDefaultDisplay();
// Set official font
officialRegularFont = Typeface.createFromAsset(this.getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(this.getAssets(), "square721extendedbold.ttf");
// Show action bar
getSupportActionBar().show();
// Inflate the custom action bar
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mCustomActionView = inflator.inflate(R.layout.actionbar_layout, null);
tvActionBarTitle = (TextView) mCustomActionView.findViewById(R.id.tv_action_bar_title);
tvActionBarTitle.setTypeface(officialBoldFont);
tvActionBarTitle.setTextColor(Color.parseColor("#000000"));
tvActionBarTitle.setTextSize(14.5f);
getSupportActionBar().setCustomView(mCustomActionView);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xffFFCC00));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
// Inflate and customise the drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setDrawerShadow(new ColorDrawable(0xffFF0000), GravityCompat.START);
drawerLayout.setBackgroundResource(R.drawable.bgnd_drawerlayout_default);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
// Inflate and customise the drawer layout list and drawer layout adapter
lvDrawerLayout = (ListView) findViewById(R.id.lv_drawer);
lvDrawerLayout.setDividerHeight(2);
// Below is the listview's bgnd and is different from bgnd_lv_item_drawerlayout.xml which is the bgnd for the items in this LV
lvDrawerLayout.setBackgroundResource(R.drawable.bgnd_lv_drawerlayout_default);
lvDrawerLayoutData = new ArrayList<DrawerLayoutDrawer>();
lvDrawerLayoutData.add(new DrawerLayoutDrawer("ADMINISTRATION", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("FINANCE CALCULATOR", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("EXIT", R.drawable.ic_test));
drawerLayoutAdapter = new DrawerLayoutAdapter(this, R.layout.lv_layout_drawer, lvDrawerLayoutData, officialRegularFont, officialBoldFont);
lvDrawerLayout.setAdapter(drawerLayoutAdapter);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Call starting fragment
if (savedInstanceState == null) {
callStartingFrag(0);
}
}
//!< Call starting fragment
public void callStartingFrag(int position) {
Bundle args = new Bundle();
fragment = new FragmentOne();
args.putString(" ", lvDrawerLayoutData.get(position).getItemName());
args.putInt(" ", lvDrawerLayoutData.get(position).getImgResID());
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
//!< Enable drawer layout
public void enableDrawerLayout() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
//!< Set custom action bar title
public void setActionBarTitle(String title){
tvActionBarTitle.setText(title);
}
//!< Return MainActivity object
public MainActivity getMainActivity() {
mainActivity = new MainActivity();
return mainActivity;
}
//!< This hook is called whenever an item in your options menu is selected. . The action bar home/up action should open or close the drawer. ActionBarDrawerToggle will take care of this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
//!< Sync the toggle state after onRestoreInstanceState has occurred. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
//!< Pass any configuration change to the drawer toggles. This method should always be called by your Activity's onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
//!< Call respective fragment
public void selectItem(int position) {
switch (position) {
case 0:
fragment = new FragmentTwo();
break;
case 1:
fragment = new FragmentThree();
break;
case 2:
finish();
break;
default:
break;
}
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
}
Drawer layout code:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/lv_drawer"
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#000000"/>
</android.support.v4.widget.DrawerLayout>
Drawer layout listview laout code:
<?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="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:id="#+id/itemLayout">
<TextView
android:id="#+id/tv_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Action bar layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent" >
<TextView
android:id="#+id/tv_action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"/>
</RelativeLayout>
1st fragment code:
public class FragmentOne extends Fragment {
ImageView ivIcon;
TextView tvAgentID;
public Typeface officialBoldFont, officialRegularFont;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_one, container, false);
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag one list item 1", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragOneClickListener());*/
//
officialRegularFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedbold.ttf");
tvAgentID = (TextView) view.findViewById(R.id.tv_agentid);
tvAgentID.setText("TESTING 1 2 3");
tvAgentID.setTypeface(officialBoldFont);
tvAgentID.setTextColor(Color.BLACK);
tvAgentID.setBackgroundColor(Color.WHITE);
tvAgentID.setTextSize(25f);
return view;
}
}
1st fragment layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<LinearLayout
android:id="#+id/ll_innerloginlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
android:padding="20dp">
<TextView
android:id="#+id/tv_agentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
2nd fragment code below:
public class FragmentTwo extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
private List<DrawerLayoutDrawer> dataList;
public FragmentTwo()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_two, container, false);
//
((MainActivity) getActivity()).setActionBarTitle("Test screen 2");
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag two list item 2", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragTwoClickListener());*/
ivIcon=(ImageView)view.findViewById(R.id.frag2_icon);
tvItemName=(TextView)view.findViewById(R.id.frag2_text);
tvItemName.setText("TESTING FRAG TWO");
tvItemName.setTextSize(45f);
tvItemName.setTextColor(Color.RED);
tvItemName.setBackgroundColor(Color.BLACK);
return view;
}
}
2nd fragment XML code:
<?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="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag2_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="200dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="0dp"/>
</LinearLayout>
3rd fragment code:
public class FragmentThree extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentThree()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_three, container, false);
ivIcon=(ImageView)view.findViewById(R.id.frag3_icon);
tvItemName=(TextView)view.findViewById(R.id.frag3_text);
tvItemName.setText("TESTING FRAG THREE");
return view;
}
}
3rd fragment XML code:
<?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="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag3_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag3_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
1st fragment listener:
public class FragOneClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragOneSelectItem(position);
}
}
2nd fragment listener:
public class FragTwoClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragTwoSelectItem(position);
}
}

How to add Overflow menu at right end in Tabs in Android Phone

I am making an android application where I need to create two Tabs that is simple I did but I need to add the OverFlow menu also in same row. See screenshot.
I never implement this in Android that might seems more tricky to me.
Please help me if you know how to achieve this in Android.
I simply achieved the Tabs using below code.
public class PayStubActivity extends ActionBarActivity implements ActionBar.TabListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // requesting to set the custom title bar
setContentView(R.layout.activity_pay_stub);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// adding action bar tabs to the activity
ActionBar mActionBar = getSupportActionBar();
Tab firstTab = mActionBar.newTab().setText(getString(R.string.paystub_current_tab)).setTabListener(this);
Tab secondTab = mActionBar.newTab().setText(getString(R.string.paystub_all_tab)).setTabListener(this);
// add the tabs to the action bar
mActionBar.addTab(firstTab);
mActionBar.addTab(secondTab);
// set the navigation mode the Action Bar Tabs
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
// user is selected first tab
if(tab.getPosition() == 0) {
fragmentTransaction.replace(R.id.container, new CurrentPayStubFragment());
} else {
// user is selected second tab.
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {}
}
Thanks in advance.
You will need a custom Layout for your Action bar:
layout_action_bar:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:showDividers="middle"
android:divider="#drawable/action_bar_divider"
android:dividerPadding="10dp"
android:weightSum="7">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:clickable="true"
android:onClick="imagesViewClick">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="IMAGES"
android:textColor="#android:color/white"
android:gravity="center"
android:layout_centerInParent="true"/>
<View
android:id="#+id/images_selected_view"
android:layout_width="match_parent"
android:layout_height="6dp"
android:layout_alignParentBottom="true"
android:background="#427fed"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:clickable="true"
android:onClick="videosViewClick">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="VIDEOS"
android:textColor="#android:color/white"
android:gravity="center"
android:layout_centerInParent="true"/>
<View
android:id="#+id/videos_selected_view"
android:layout_width="match_parent"
android:layout_height="6dp"
android:layout_alignParentBottom="true"
android:background="#427fed"
android:visibility="gone"/>
</RelativeLayout>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_overflow"
android:layout_gravity="center_vertical"
android:layout_weight="1"/>
</LinearLayout>
And then your Activity Implementation:
public class MainActivity extends ActionBarActivity{
private View imagesViewSelected;
private View videosViewSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ImagesFragment())
.commit();
}
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
ActionBar.LayoutParams lp1 = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
View customNav = LayoutInflater.from(this).inflate(R.layout.layout_action_bar, null);
imagesViewSelected = customNav.findViewById(R.id.images_selected_view);
videosViewSelected = customNav.findViewById(R.id.videos_selected_view);
actionBar.setCustomView(customNav, lp1);
}
public static class ImagesFragment extends Fragment {
public ImagesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
((TextView)rootView.findViewById(R.id.txt_fragment_locator)).setText("Images Fragment");
return rootView;
}
}
public static class VideosFragment extends Fragment {
public VideosFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
((TextView)rootView.findViewById(R.id.txt_fragment_locator)).setText("Videos Fragment");
return rootView;
}
}
public void imagesViewClick(View view){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new ImagesFragment())
.commit();
imagesViewSelected.setVisibility(View.VISIBLE);
videosViewSelected.setVisibility(View.GONE);
}
public void videosViewClick(View view){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new VideosFragment())
.commit();
imagesViewSelected.setVisibility(View.GONE);
videosViewSelected.setVisibility(View.VISIBLE);
}
}
Gabriele Mariotti's Cardslib has a good implementation thereof in the CardView class.
The CardView consists of a CardHeader which provides an overflow button with a PopupMenuListener, a button to expand/collapse an area, or a customizable button with its listener.
The CardHeader will greatly assist you in this regard. CardHeader source code
HTH

Childfragment not updating ActionBar when resumed after back-press in FragmentStatePagerAdapter

I have a small problem with my application which uses a FragmentStatePagerAdapter when scrolling between pages.
First I'll describe how the application is built with a stripped down version.
App description
I have one Activity which holds everything together. This Activity in turn hosts a Fragment, in this case called Pager.
This Pager-class has a ViewPager within, with a FragmentStatePagerAdapter as an inner class which is used to provide the fragments for the ViewPager. The fragments provided to the ViewPager are instances of FragmentA.
FragmentA has its own content and its own items on the ActionBar, but can also in turn open other fragments. In my "Real" application this can be done either by clicking some item in a ListView or by clicking a button on the ActionBar. In this simplified case FragmentA can open up FragmentB via a button.
So far this works just as it should.
Problem
When FragmentB is opened from any of the FragmentA-fragments it is properly displayed with its own content and menu in the ActionBar, replacing the menu of FragmentA. However, when navigating back via the back-button the ActionBar for FragmentA is never restored to the state the FragmentA-actionbar had prior to opening FragmentB, instead it's empty.
Possibly strange behaviour
When I change so that MainPagerAdapter extends FragmentPagerAdapter instead of FragmentStatePagerAdapter, all of a sudden it works just fine, and I really don't understand why this is. Also, manually calling supportInvalidateOptionsMenu() did not work at all when the Fragment was contained within a FragmentStatePagerAdapter.
I looked in to the source of both of the adaptertypes but I couldn't figure out why one of them worked while the other didn't.
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.addToBackStack("Start")
.replace(R.id.container, new Pager())
.commit();
}
public void openB() {
getSupportFragmentManager()
.beginTransaction()
.addToBackStack("Start1")
.replace(R.id.container, new FragmentB())
.commit();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/container">
</RelativeLayout>
Pager.java
public class Pager extends Fragment {
ViewPager mViewPager;
MainPagerAdapter mainPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.wrapper_layout, null);
mViewPager = (ViewPager)v.findViewById(R.id.viewpager);
mainPagerAdapter = new MainPagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(mainPagerAdapter);
return v;
}
private class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new FragmentA();
}
#Override
public int getCount() {
return 2;
}
}
}
wrapper_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
FragmentA.java
public class FragmentA extends Fragment {
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
menu.add("A-Menu");
}
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.a, null);
Button b = (Button)v.findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().supportInvalidateOptionsMenu();
}
});
Button b2 = (Button)v.findViewById(R.id.button);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).openB();
}
});
return v;
}
}
a.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B"
android:id="#+id/button"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Invalidate"
android:id="#+id/button2"
android:layout_gravity="right"
/>
</LinearLayout>
FragmentB.java
public class FragmentB extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
menu.add("B-Menu");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.b, null);
return v;
}
}

how to rename tab android use tabhost and long click

I have designed an app in that I am using Tabhost and I have added two tabs. I want rename tab Device1 when "long click" this tab. I try some way but it is not working. I have implemented following:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabHost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<HorizontalScrollView
android:id="#+id/horScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/Device1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingTop="80px" >
</LinearLayout>
<LinearLayout
android:id="#+id/Device2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingTop="80px" >
</LinearLayout>
</FrameLayout>
MainActivity.java
package com.example.renametab;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
public class MainActivity extends Activity {
public static TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabSpec tabDevice1 = tabHost.newTabSpec("Device1");
tabDevice1.setContent(R.id.Device1);
tabDevice1.setIndicator("Device1");
TabSpec tabDevice2 = tabHost.newTabSpec("Device2");
tabDevice2.setContent(R.id.Device2);
tabDevice2.setIndicator("Device2");
tabHost.addTab(tabDevice1);
tabHost.addTab(tabDevice2);
tabHost.getTabWidget().getChildAt(0).setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//How to rename tab????
//I try this way but it is false
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(0).findViewById(R.id.Device1);
tv.setText("New Name Tab");
return true;
}
});
}
#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;
}
}
On close inspection using the Android Studio debugger, each tab contained in TabWidget is a LinearLayout with 2 children:
An ImageView with the id android.R.id.icon;
A TextView with the id android.R.id.title.
Knowing this, we can find each tab's title TextView, set an OnLongClickListener on each tab, and then modify the title using TextView.setText().
Here's my Fragment's onCreateView() method, defining 3 tabs, each implementing this functionality:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mTabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabHost.addTab(mTabHost.newTabSpec(TAB_1).setIndicator("Tab 1").setContent(R.id.tab_1));
mTabHost.addTab(mTabHost.newTabSpec(TAB_2).setIndicator("Tab 2").setContent(R.id.tab_2));
mTabHost.addTab(mTabHost.newTabSpec(TAB_3).setIndicator("Tab 3").setContent(R.id.tab_3));
LinearLayout tabOne = (LinearLayout) mTabHost.getTabWidget().getChildTabViewAt(0);
final TextView tabOneTitle = (TextView) tabOne.findViewById(android.R.id.title);
LinearLayout tabTwo = (LinearLayout) mTabHost.getTabWidget().getChildTabViewAt(1);
final TextView tabTwoTitle = (TextView) tabTwo.findViewById(android.R.id.title);
LinearLayout tabThree = (LinearLayout) mTabHost.getTabWidget().getChildTabViewAt(2);
final TextView tabThreeTitle = (TextView) tabThree.findViewById(android.R.id.title);
tabOne.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
tabOneTitle.setText("New Tab 1");
return true;
}
});
tabTwo.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
tabTwoTitle.setText("New Tab 2");
return true;
}
});
tabThree.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
tabThreeTitle.setText("New Tab 3");
return true;
}
});
return rootView;
}
Here are before and after screenshots documenting the results:
Simply use the onTabChanged event:
TabHost th = new findViewById(android.R.id.tabhost);
th.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(final String tabId) {
TextView tv = (TextView) th.getCurrentView();
tv.setText("New Name Tab");
}
});
<TextView
android:id="#+id/textView1"
android:layout_width="204dp"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:text="TAB 1"/>
Add a TextView in both the linear layouts in the xml file and set their text dynamically using Tab Change Listener :-
TabHost tabHost = new findViewById(android.R.id.tabHost1);
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(final String tabId) {
TextView textView1 = (TextView) tabHost.getCurrentView();
textView1.setText("This Tab is Selected");
}
});

Fragments overlapping using ListFragment and FragmentTabHost

My FragmentTabHost and ListView works fine until I clicked an item in ListView then change Tab.That is when the Fragments overlap.
Here is the image after clicking an item in ListView then changing from Tab 1(where the ListView resides) to Tab 2(another fragment is called).
http://i904.photobucket.com/albums/ac243/fookywooky/OverlappingFragments_zps2b60e9ab.png
Here is my main activity
public class MainActivity extends FragmentActivity {
private FragmentTabHost hostTab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hostTab = (FragmentTabHost)findViewById(android.R.id.tabhost);
//hostTab = (TabHost) findViewById(R.id.tabhost);
hostTab.setup(this,getSupportFragmentManager(), android.R.id.tabcontent);
hostTab.addTab(
hostTab.newTabSpec("tab1").setIndicator("Tab 1",
getResources().getDrawable(android.R.drawable.star_on)),
FragmentTab.class, null);
hostTab.addTab(
hostTab.newTabSpec("tab2").setIndicator("Tab 2",
getResources().getDrawable(android.R.drawable.star_on)),
FragmentTab1.class, null);
hostTab.addTab(
hostTab.newTabSpec("tab3").setIndicator("Tab 3",
getResources().getDrawable(android.R.drawable.star_on)),
FragmentTab2.class, null);
}
And here is my fragment for Tab 1(with ListView)
public class FragmentTab extends ListFragment implements OnItemClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] values = new String[] { "Ang na Ang na", "Sulakihin", "Somaskidot", "Moko Moko"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
switch(position){
case 0:
// Create new fragment and transaction
Fragment newFragment = new FragmentInListView();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.tabcontent, newFragment);
transaction.addToBackStack(null);
transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// Commit the transaction
transaction.commit();
break;
default:
}
}
}
I just added 1 fragment for 1 item in the ListView for testing. Still no fragments for Items 2,3 and 4.
Here is my code for the Tab 2.
public class FragmentTab1 extends Fragment {
FragmentActivity main;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_layout1,
container, false);
TextView tv= (TextView) view.findViewById(R.id.text);
tv.setText("Fragment 2");
return view;
}
}
And here is my activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/replace"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
And here is the xml file for the list view fragment.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:id="#+id/tanga" >
<ListView
android:id="#+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
and lastly, here is the xml for Tab 2
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:id="#+id/bobo">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="#string/hello_world"
android:textAppearance="?android:attr/textAppearanceMedium" />
Just feel free to ask if you want anymore code to be posted. I will be grateful for any help or comments. Please help. Thanks in advance.

Categories

Resources