How to transfer variables to a fragment was created using the ActionBarActivity? - android-fragments

The activity is called from another activity delivering a string array, which needs to be displayed in a fragment of the target activity.
MainActivity (string array) -> Result2Activity: Tab1 should display string index0, Tab2 should display string index1 etc.
I followed a similar problem here:
Access Fragment View from Activity's onCreate
My problem is right now that the onActivityCreated method is never called in the Result2Activity.
I am also not sure if this method is the right way to address the fragment:
getSupportFragmentManager().findFragmentByTag("Out1");
What is the best way to achieve that ?
Result2Activity:
public class Result2Activity extends ActionBarActivity 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.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
public List<String> fragments = new Vector<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result2_activity);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// 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.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));
}
Log.d("DEBUG","1: onCreate finished");
}
public void onActivityCreated (Bundle savedInstanceState) {
Log.d("DEBUG","2: onActivityCreated finished");
//super.onActivityCreated(savedInstanceState);
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
//send data to fragment Out1Fragment
Out1Fragment set_out1 =
(Out1Fragment)
getSupportFragmentManager().findFragmentByTag("Out1");
set_out1.settext(message[0]);
}
#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) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
fragments.add(Out1Fragment.class.getName());
fragments.add(Out2Fragment.class.getName());
fragments.add(Out3Fragment.class.getName());
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Out1Fragment();
break;
case 1:
fragment = new Out2Fragment();
break;
case 2:
fragment = new Out3Fragment();
break;
}
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 getString(R.string.out_section1).toUpperCase(l);
case 1:
return getString(R.string.out_section2).toUpperCase(l);
case 2:
return getString(R.string.out_section3).toUpperCase(l);
}
return null;
}
}
}
Out1Fragment:
public class Out1Fragment extends Fragment {
private static TextView textview;
public Out1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.out1_fragment, container,
false);
textview = (TextView) dataView.findViewById(R.id.outPut1);
return dataView;
}
public void settext(String text)
{
textview.setText(text);
}
}
XML Resource:
result2_activity.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dd.testing.finance.Result2Activity" />
out1_fragment.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ScrollView2"
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"
android:tag="Out1"
tools:context="dd.testing.finance.Result2Activity$Out1Fragment" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/outPut1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>

Not really sure if this was the right way, but at least it does exaclty what I needed.
In the Out1Fragment.class added the onActivityCreated method:
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
settext(((Result2Activity)getActivity()).getOutput1());
}
From there calling the added method getOutput1 in the Result2Activity:
public String getOutput1 () {
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
return message[0];
}

Related

Firebase ui 3.1.0 (Firebaselistadapter) No setter/field for mc_name found on class

I've tried my code in normal activity both images and text show. in fragment only image showing but the text is not showing (in both normal and fragment activity I've used same xml layout). I'm using firebaselistadpter for gridview and it works fine. I also tried using it with listview in fragment still images only showing but no text showing. (there is no Error message).
1- my java activity:
public class R_MainCat extends Fragment {
private GridView gridView;
private DatabaseReference myRef;
private FirebaseListAdapter<Sub_Category_Data> adapter;
private TextView mc_name;
private ImageView url;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview, container, false);
rootView.setBackgroundColor(Color.WHITE);
myRef= FirebaseDatabase.getInstance().getReference("Main_Category");
Firebase.getDefaultConfig().setPersistenceEnabled(true);
gridView = (GridView) rootView.findViewById(R.id.gridview);
FirebaseListOptions<Sub_Category_Data> options = new FirebaseListOptions.Builder<Sub_Category_Data>()
.setQuery(myRef, Sub_Category_Data.class).setLayout(R.layout.gridview_icon).build();
adapter = new FirebaseListAdapter<Sub_Category_Data>(options) {
#Override
protected void populateView(View v, Sub_Category_Data model, int position) {
mc_name = v.findViewById(R.id.cat_name);
url = v.findViewById(R.id.img);
mc_name.setText(model.getName());
Picasso.with(getActivity()).load(model.getUrl()).into(url);
}
};
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch(i)
{
case 0:
R_DairyProds f1 = new R_DairyProds();
FragmentTransaction fragTransaction1 = getFragmentManager().beginTransaction();
fragTransaction1.replace(R.id.container_view,f1 );
fragTransaction1.addToBackStack(null);
fragTransaction1.commit();
break;
case 1:
R_Bakery f2 = new R_Bakery();
FragmentTransaction fragTransaction2 = getFragmentManager().beginTransaction();
fragTransaction2.replace(R.id.container_view,f2 );
fragTransaction2.addToBackStack(null);
fragTransaction2.commit();
break;
case 2:
R_Grocery f3 = new R_Grocery();
FragmentTransaction fT3 = getFragmentManager().beginTransaction();
fT3.replace(R.id.container_view,f3);
fT3.addToBackStack(null);
fT3.commit();
break;
case 3:
R_FruitsNVegs f4 = new R_FruitsNVegs();
FragmentTransaction fT4 = getFragmentManager().beginTransaction();
fT4.replace(R.id.container_view,f4);
fT4.addToBackStack(null);
fT4.commit();
break;
case 4:
R_CleanNWash f5 = new R_CleanNWash();
FragmentTransaction fT5 = getFragmentManager().beginTransaction();
fT5.replace(R.id.container_view,f5);
fT5.addToBackStack(null);
fT5.commit();
break;
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
2-my xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<me.grantland.widget.AutofitLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/img"
>
<TextView
android:id="#+id/cat_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello_world"
android:textColor="#000"
android:textSize="20sp"
android:gravity="center"
/>
</me.grantland.widget.AutofitLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
3- my Data model java:
public class Sub_Category_Data {
private String mc_name;
private String url;
public Sub_Category_Data() {
}
public void setName(String mc_name) {
this.mc_name = mc_name;
}
public String getName() {
return mc_name;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
4- snapshot of the output:
text suppose to be showing under the image.
Output in fragment
I want my fragment to show the text data same as what is showing in this image
Output I've tested in normal Activity
5- database snapshot:
Database Image
does anyone have any clue? or have faced this issue before? because I'm lost since there is no error showing besides the fact it works fine in normal activity but text is not showing in the fragment. thank you in advance.
after looking over and over I noticed this in logcat
"No setter/field for mc_name found on class"
I've fixed the problem. It was in the model class getName() and SetName() methods I changed them to same name as the child key name in my firebase you can see picture of the database in the question above. so the new methods are getMc_name() and setMc_name().
public class Sub_Category_Data {
private String mc_name;
private String url;
public Sub_Category_Data() {
}
public String getMc_name() {
return mc_name;
}
public void setMc_name(String mc_name) {
this.mc_name = mc_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
the output screen shot

Working with fragments - findViewById returns NULL on Button in Android

I've started dealing with Fragments in Android. I created Activity with NavigationView which has 3 items and worked with 3 simple fragments till now. NavigationHeader has 2 buttons - 1 starts LoginActivity and 2nd RegisterActivity. I remind that everything till niw worked fine. Today I've tried to create RecyclerView inside one of the fragments. Now when I try to run app, findViewById applied to those 2 NavigationHeader buttons returns NULL. I have no idea why.
Here is HomeActivity:
public class HomeActivity extends AppCompatActivity {
private static final String FRAGMENT_POSITION = "fragment_position"; // Fragment Position
private DrawerLayout mDrawerLayout; // NavigationDrawer Layout
private NavigationView nvDrawer; // NavigationView
private CoordinatorLayout homeCoordinatorLayout; // Coordinator Layout For Snackbar
private Toolbar toolbar; // Application Toolbar
private TextView navHeaderNamePlusSurname; // Name And Surname Navigation Header Text
private TextView navHeaderEmail; // E-mail Navigation Header Text
AppCompatButton navHeaderButtonLogin; // Login/Logout Button
AppCompatButton navHeaderButtonRegister; // Register Button
private ActionBarDrawerToggle mDrawerToggle; // ActionBar Drawer Toggle
private SQLiteHandler db; // SQLite Database Helper Class
private SessionManager session; // Session Manager
private int lastShownFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Setting Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Setting Up DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = setupDrawerToggle();
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Navigation Header Logout Button
navHeaderButtonLogin = (AppCompatButton) findViewById(R.id.nav_header_btn_log_in_out);
navHeaderButtonRegister = (AppCompatButton) findViewById(R.id.nav_header_btn_register);
Log.d("czy_null", "navHeaderButtonLogin: " + navHeaderButtonLogin + ", navHeaderButtonRegister: " + navHeaderButtonRegister);
// Name, Surname And E-mail Texts
navHeaderNamePlusSurname = (TextView) findViewById(R.id.nav_header_name_plus_surname);
navHeaderEmail = (TextView) findViewById(R.id.nav_header_email);
// SQLite Database Handler
db = new SQLiteHandler(getApplicationContext());
// Session Manager
session = new SessionManager(getApplicationContext());
// Navigation Drawer
nvDrawer = (NavigationView) findViewById(R.id.navigation_view);
// Checking If User Is Logged In
if (!session.isLoggedIn()) {
hideNavigationViewGroup(nvDrawer); // Hiding NavigationView Group Depending
// If Not Logged
} else {
navHeaderButtonLogin.setText(getText(R.string.home_btn_log_out));
navHeaderButtonRegister.setVisibility(View.INVISIBLE);
// Fetching User Details From SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get(SQLiteHandler.KEY_NAME);
String surname = user.get(SQLiteHandler.KEY_SURNAME);
String email = user.get(SQLiteHandler.KEY_EMAIL);
// Setting Navigation Header Texts
String nameSurname = name + " " + surname;
navHeaderNamePlusSurname.setText(nameSurname);
navHeaderEmail.setText(email);
}
// Setting Up CoordinatorLayout
homeCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.home_coordinator_layout);
// Setting Listener To NavigationView
setupDrawerContent(nvDrawer);
// Setting Starting Fragment
if (savedInstanceState == null) {
setStartingFragment();
} else {
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Applying Login/Logout Button Listener
setLoginButtonListener();
// Applying Register Button Listener
setRegisterButtonListener();
}
// Listener To Login/Register Button
private void setLoginButtonListener() {
navHeaderButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!session.isLoggedIn()) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
} else {
mDrawerLayout.closeDrawers();
logoutUser();
navHeaderNamePlusSurname.setText(getString(R.string.nav_header_name_surname));
navHeaderEmail.setText(getString(R.string.nav_header_email));
hideNavigationViewGroup(nvDrawer);
navHeaderButtonLogin.setText(getString(R.string.home_btn_log_in));
navHeaderButtonRegister.setVisibility(View.VISIBLE);
showSnackbarInfo(getString(R.string.inf_logout_success),
R.color.snackbar_success_msg);
}
}
});
}
// Listener To Register Button
private void setRegisterButtonListener() {
navHeaderButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
}
// Logging Out The User
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
}
// Setting Up DrawerToggle
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
R.string.drawer_close);
}
// Setting Up Drawer Content
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
// Replace Existing Fragment With a New One
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_top20_recipes: {
fragmentClass = Top20RecipesFragment.class;
lastShownFragment = 0;
break;
}
case R.id.nav_kitchen_type: {
fragmentClass = KitchenTypeFragment.class;
lastShownFragment = 1;
break;
}
case R.id.nav_meal_type: {
fragmentClass = MealTypeFragment.class;
lastShownFragment = 2;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
mDrawerLayout.closeDrawers(); // Close The Drawer
}
// Function Setting First Fragment
private void setStartingFragment() {
Fragment fragment = null;
Class fragmentClass = Top20RecipesFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = 0;
MenuItem menuItem = nvDrawer.getMenu().getItem(0);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
}
// Saving Fragment Title State
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(FRAGMENT_POSITION, lastShownFragment);
}
// Restoring Fragment Title States
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Restoring Selected Item On Screen Rotation Or App Minimalize
private void restoreOnInstanceState(int lastPosition) {
Fragment fragment = null;
Class fragmentClass = null;
switch (lastShownFragment) {
case 0: {
fragmentClass = Top20RecipesFragment.class;
break;
}
case 1: {
fragmentClass = KitchenTypeFragment.class;
break;
}
case 2: {
fragmentClass = MealTypeFragment.class;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = lastPosition;
MenuItem menuItem = nvDrawer.getMenu().getItem(lastPosition);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Function Hiding Items In NavigationView
private void hideNavigationViewGroup(NavigationView nvDrawer) {
nvDrawer.getMenu().setGroupVisible(R.id.nav_group_logged_user, false);
}
// Function Showing Snakcbar
private void showSnackbarInfo(String info, int textColor) {
Snackbar snackbar = Snackbar.make(homeCoordinatorLayout, info, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView sbText = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
sbText.setTextColor(ContextCompat.getColor(getApplicationContext(), textColor));
snackbar.show();
}
}
Here is my fragment which has to contain RacyclerView:
public class KitchenTypeFragment extends Fragment {
RecyclerView kitchenTypeRecycleView;
private ArrayList<KitchenTypeItem> kitchenTypeItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
kitchenTypeItems = new ArrayList<>();
fillKitchenTypeArray(kitchenTypeItems);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kitchen_type, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
kitchenTypeRecycleView = (RecyclerView) view.findViewById(R.id.kitchen_type_recycle_view);
kitchenTypeRecycleView.setHasFixedSize(true);
kitchenTypeRecycleView.setAdapter(new KitchenTypeAdapter(kitchenTypeItems,
R.layout.kitchen_type_grid_item));
kitchenTypeRecycleView.setLayoutManager(new GridLayoutManager(getContext(), 2));
kitchenTypeRecycleView.setItemAnimator(new DefaultItemAnimator());
}
private void fillKitchenTypeArray( ArrayList<KitchenTypeItem> kitchenTypeItems) {
KitchenTypeItem kitchenItem;
// Currently 8 Kitchen Types
String[] itemNames = getResources().getStringArray(R.array.kitchen_types);
// Filling ArrayList
for(int i = 0; i < itemNames.length; i++) {
kitchenItem = new KitchenTypeItem(itemNames[i], R.drawable.example_kitchen_type);
kitchenTypeItems.add(kitchenItem);
}
}
}
Here is XML from HomeActivity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/home_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegisterActivity">
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".SignUpActivity">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/frame_layout_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
Here is NavigationHeader XML with those 2 buttons:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relative_nav_header"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="#color/primary"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="40dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical">
<!-- Name + Surname, E-mail -->
<LinearLayout
android:id="#+id/nav_lin_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:orientation="vertical">
<!-- Name + Surname Text -->
<TextView
android:id="#+id/nav_header_name_plus_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textSize="17sp"
android:text="#string/nav_header_name_surname" />
<!-- E-mail Adress -->
<TextView
android:id="#+id/nav_header_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/accent"
android:fontFamily="sans-serif"
android:textSize="13sp"
android:text="#string/nav_header_email" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp"
android:gravity="center|left"
android:layout_below="#+id/nav_lin_layout">
<!-- Login/Logut Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_log_in_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_login_color"
android:textColor="#color/text_icons"
android:stateListAnimator="#null"
android:text="#string/btn_log_in" />
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_register_color"
android:stateListAnimator="#null"
android:textColor="#color/text_icons"
android:text="#string/btn_sign_up" />
</LinearLayout>
</RelativeLayout>
And here is finally XML from Fragment:
<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"
android:id="#+id/kitchen_type_fragment"
android:padding="16dp"
tools:context="com.example.nazwamarki.myapplication.fragments.KitchenTypeFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/kitchen_type_recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
You should use findViewById on the headerView like this:
navigationView.getHeaderView(0).findViewById()

How to get a fragment to display after it is called by another fragment (via Activity)

I am at ends wit with my code. I can not get a fragment to display after it is called by another fragment (via Activity). I read the Android Developer guide and many SO's related topic on Fragment/FragmentPagerAdapter/FragmentTransactions and could not resolve my issue. This one would have been an obvious solution Is it possible to remove a fragment without replacing it by another fragment
I have an activity class that will host a fragment based on the tab selected. These fragments are dynamically created by the FragmentPagerAdapter based on user's selection of the tab. In the first tab, it creates FragmentA (ListFragment) which consists of a list of items. When a user clicks on any of the item, it should display another fragment with that item's details but to much of my dismay (and eyes burning), all it does is print out my log in logcat. Please see my code. Perhaps, I am staring at it too long and/or just don't know enough of android to see what's going on. I suspect it has to do with this line: fragTransaction.replace(R.id.curriculumParent, fragC); Now I know this would work if the 1st parameter was a fragment container in the activity's layout file was define but since it is not done statically, I don't know what to put there except for the calling FragmentB's layout file.
Thanks in advance!
MainActivity.java
public class MainActivity extends FragmentActivity implements
FragmentB.OnColorSelectedListener {
private static final String TAG = "MainActivity";
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
adapter = new MyPagerAdapter(fm);
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
getResources().getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
...
...
...
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "FragmentB", "2ndTabFragment", "3rdTabFragment" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = Fragment.instantiate(getBaseContext(), FragmentB.class.getName());
break;
case 1:
fragment = Fragment.instantiate(getBaseContext(), SecondTabFragment.class.getName());
break;
case 2:
fragment = Fragment.instantiate(getBaseContext(), ThirdTabFragment.class.getName());
break;
}
return fragment;
}
}
#Override
public void onColorLevelSelected(int position)
{
Log.i(TAG, "Got Here!");
FragmentC fragC = new FragmentC();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragTransaction = fm.beginTransaction();
**fragTransaction.replace(R.id.curriculumParent, fragC);**
fragTransaction.addToBackStack(null);
fragTransaction.commit();
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tabs" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
FragmentB.java
public class FragmentB extends ListFragment{
OnColorSelectedListener mCallback;
private String[] colorLevel = new String[]{
"Yellow",
"Orange",
"Green",
"Blue",
"pink",
"Black"
};
private int[] colorImages = new int[]{
R.drawable.yellow,
R.drawable.orange,
R.drawable.green,
R.drawable.blue,
R.drawable.pink,
R.drawable.black
};
public interface OnColorSelectedListener{
public void onItemLevelSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
List<HashMap<String, String>> colorList = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 6; i++){
HashMap<String, String> colorMap = new HashMap<String, String>();
colorMap.put("lvl", colorLevel[i]);
colorMap.put("img", Integer.toString(colorImages[i]));
colorList.add(colorMap);
}
String[] from = {"img", "lvl"};
int[] to = {R.id.colorLevelImg, R.id.colorLevelTxt};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mCallback = (OnColorSelectedListener) activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement OnColorSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos],
Toast.LENGTH_LONG).show();
mCallback.onColorLevelSelected(pos);
}
}
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
**android:id="#+id/curriculumParent"**
...
...
android:background="#FEFDFB">
<ImageView
android:id="#+id/colorLevelImg"
...
android:paddingBottom="10dp" />
<LinearLayout
...
android:orientation="vertical" >
<TextView
android:id="#+id/colorLevelTxt"
...
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
FragmentC.java
public class FragmentC extends Fragment{
public static final String TAG = "Fragment C";
public FragmentC(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.i(TAG, "HI");
return inflater.inflate(R.layout.fragment_c, container, false);
}
}
fragment_c.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCC00" >
<TextView
android:id="#+id/editText1"
...
android:layout_margin="16dp"
android:text="This is the C Fragment that will replace the B Fragment" >
</TextView>
</RelativeLayout>
I noticed FragmentB.java does not explicitly point to any layout file to inflate. In case you don't know,
ListFragment has a default layout that consists of a single list view
, documented # ListFragment. So you're still fine if you only want a simple ListView, but maybe NOT. But then you have code that references another layout to FragmentB:
new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b...
Note: R.layout.fragment_b is the layout specified for the ArrayAdapter only! Not for the fragment. But this is normal and may be fine.
In MainActivity, onColorLevelSelected():
fragTransaction.replace(R.id.curriculumParent,...
Note:
I think this replaces the layout only for the adapter and not the fragment.
Perhaps you want to inflate a layout file containing a ListView, and use that for the fragments.
Your problem is basically the layout, work with that.
EDIT:
Code suggestion:
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_x
public void onColorLevelSelected(int position)
FragmentC fragX = new FragmentX();
...
fragTransaction.replace(R.id.curriculumParent, fragX);
Notes:
Notice I am using an example of an arbitrary FragmentX. The Adapter and the replace() matches each other.
I understand this code change is somewhat considerable. Since I said it, here is a new code suggestion:
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos], Toast.LENGTH_LONG).show();
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
...
setListAdapter(adapter);
...
mCallback.onColorLevelSelected(pos); }
Note: This code change is made only to be simpler, my attempt. The idea is when the user click on a row in ListView, you know which layout and fragment is used. Hopefully that makes code less complicated.

How to load a fragment view in a tab

I am trying to create tabs inside a fragment. I manage to create tab inside the fragment, but now I want to load different fragment for each tab (fragment1.class and fragment2.class).
Can anybody please suggest how can i load each fragment to their respective tabs?
Below is my main fragment that is holding the tabs.
Thanks a lot!
public class BusFragment extends Fragment {
private TabHost mTabHost;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bus, container, false);
mTabHost = (TabHost) rootView.findViewById(R.id.tabHost);
mTabHost.setup();
TabHost.TabSpec spec = mTabHost.newTabSpec("tag");
spec.setIndicator("Fragment1");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag1");
spec.setIndicator("Fragment2");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag2");
spec.setIndicator("Fragment3");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
return rootView;
}
}
Hello If you want to load the fragment inside the fragment android provide the Child Fragment Manager instead of ordinary fragment manager. I had the same issue I had the fragment inside that tab when click on tab want to load the different fragments. see the below steps hope will help you.
Step 1. See I have StatisticsFragment with it layout fragment_statistics.
public class StatisticsFragment extends Fragment {
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_statistics,container, false);
mTabHost = (FragmentTabHost) rootView.findViewById(R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),R.id.tabFrameLayout);
mTabHost.addTab(mTabHost.newTabSpec("WEEK").setIndicator(buildTabLayout(EnumStatistics.WEEKLY)),WeekFragment_.class, null);
mTabHost.addTab(mTabHost.newTabSpec("ALL").setIndicator(buildTabLayout(EnumStatistics.ALL)),DetailedFragment_.class, null);
mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new WeekTabClick());
mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new AllTabClick());
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
private View buildTabLayout(EnumStatistics enumStatistics) {
View tab;
if (enumStatistics == EnumStatistics.WEEKLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_week_layout, null);
} else if (enumStatistics == EnumStatistics.MONTHLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_month_layout, null);
} else if (enumStatistics == EnumStatistics.YEAR) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_year_layout, null);
} else {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_detailed_layout, null);
}
return tab;
}
public class WeekTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(0);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.tabFrameLayout, WeekFragment_.instantiate(getActivity(), WeekFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
public class AllTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(1);
FragmentTransaction ft = getChildFragmentManager()
.beginTransaction();
ft.replace(R.id.tabFrameLayout, DetailedFragment_.instantiate(
getActivity(), DetailedFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
}
In above buildTabLayout function intent to build the custom layout of tab widget you can put simple text or image that you want to show inside the tab widget.
Steps 2. fragment_statistics.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:relaxis="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/croutonview"
android:gravity="center" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
/>
<FrameLayout
android:id="#+id/tabFrameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</RelativeLayout>
As you see in the above inside the layout tabFrameLayout we load the all child fragment Programmaticly.
Let me know if you have any question and doubt. thank you

Customizing the fonts?

How to customize the ttf fonts on tab fragments? I am using sherlockactionbar.
Here is my code,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<FrameLayout
android:id="#+id/ptr_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
And in Main activity am using,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** to check whether user logged in or not */
session = new TwitterHomeActivity(getApplicationContext());
session.checklogin();
/** Getting a reference to action bar of this activity */
mActionBar = getSupportActionBar();
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mActionBar.setDisplayOptions(0, ActionBar.DISPLAY_USE_LOGO);
/** Set tab navigation mode */
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/** Getting a reference to ViewPager from the layout */
mPager = (ViewPager) findViewById(R.id.pager);
/** Getting a reference to FragmentManager */
FragmentManager fm = getSupportFragmentManager();
/** Defining a listener for pageChange */
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
setTitle(getTitleFromPosition(position));
mActionBar.setSelectedNavigationItem(position);
// mActionBar.setBackgroundDrawable(R.drawable.ic_action_chance_icon);
}
private CharSequence getTitleFromPosition(int position) {
if (position == 0) {
title = "text";
} else if (position == 1) {
title = "text";
} else if (position == 2) {
title = "text";
} else if (position == 3) {
title = "text";
}
return title;
}
};
/** Setting the pageChange listner to the viewPager */
mPager.setOnPageChangeListener(pageChangeListener);
/** Creating an instance of FragmentPagerAdapter */
MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
fm);
/** Setting the FragmentPagerAdapter object to the viewPager object */
mPager.setAdapter(fragmentPagerAdapter);
mActionBar.setDisplayShowTitleEnabled(true);
/** Defining tab listener */
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
/**/
Tab tab = mActionBar.newTab();
tab = mActionBar.newTab();
tab.setText(“text”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(“ttext”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(“text”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(“text”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class
.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {
// Ignore
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
startActivity(new Intent(MainActivity.this, Request_Broadcast.class));
overridePendingTransition(R.anim.right_slide_in,
R.anim.right_slide_out);
return true;
case R.id.find_people:
startActivity(new Intent(MainActivity.this, Find_people.class));
overridePendingTransition(R.anim.right_slide_in,
R.anim.right_slide_out);
return true;
case R.id.action_settings:
startActivity(new Intent(MainActivity.this, Pro_settings.class));
overridePendingTransition(R.anim.right_slide_in,
R.anim.right_slide_out);
return true;
}
return true;
}
#SuppressLint("NewApi")
public void setActionBarTitle(int feedPage) {
getActionBar().setTitle(feedPage);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
}
}
Now i want to customize the fonts on tab using typeface. How to do that and the text on tabs is displaying in uppercase letters. I want to display that in lowercase letters..
Here you have an efficent way to change the font for the entire application: Access a typeface once from asset and use it as a reference
EDIT
You can use the source code of the class I refer you to the link above. Now what you can do is change the font recursively starting from the parent layout and descending for each of their children. You should be aware that any view that can contain text is directly or indirectly a subclass of the TextView class (ie Button, EditText, CheckBox, CompoundButton, RadioButton, ToggleButton, etc). If you want to use different fonts in your application you can use for example the tag property of the view to define the font that will have that particular view. An example layout would look like this:
activity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="title"
android:text="This is the title screen" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="content"
android:text="This is the activity content." />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="content"
android:text="This is a button" />
Below this is the recursive method through which you can change the font of all views of the activity. This method is an additional method defined in class FontUtils:
public static void setActivityTypeFace(Context context, ViewGroup viewGroup) {
Object tagAux;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View viewChild = viewGroup.getChildAt(i);
if (viewChild instanceof ViewGroup) {
setActivityTypeFace(context, (ViewGroup) viewChild);
} else if (viewChild instanceof TextView) {
tagAux = viewChild.getTag();
if (tagAux != null) {
if (((String) tagAux).compareTo("title") == 0)
{
((TextView) viewChild).setTypeface(getTypeface(context,
FontType.TITLE_FONT.toString()));
}
} else if (((String) tagAux).compareTo("content") == 0) {
((TextView) viewChild).setTypeface(getTypeface(context,
FontType.CONTENT_FONT.toString()));
}
}
}
}
MainActivity.java
public class MainActivity extends Activity
private ViewGroup mRootView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRootView = (ViewGroup) findViewById(R.id.rootView);
...
FontUtil.setActivityTypeFace(this, mRootView);
}
}

Resources