Navigation between fragments java.lang.IllegalStateException - android-fragments

i have a navigation drawer and 2 fragments, by default 1 of the fragment its shown and load a list, i want to change the fragment when the user select any object of the list but i have no idea how to change the fragment, i made a method inside the drawer and calle it when a object its selected but i get java.lang.IllegalStateException, here its the code
Main drawer:
public class DrawerPrincipal extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_principal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//cargar fragment principal usuario
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//fragmento del chofer
Fragment fragmento= null;
fragmento = new FragmentoPrincipalChofer();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_main, fragmento)
.commit();
}
public void cambiarFragmento(){
Fragment fragmento;
fragmento = new PruebaUsuario();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_main, fragmento)
.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pantalla_principal_usuario, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.cuenta) {
Fragment fragmento= null;
fragmento = new OpcionDrawerUsuario();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_main, fragmento)
.commit();
} else if (id == R.id.historial_viajes) {
Fragment fragmento= null;
fragmento = new FragmentoViajesAcumulados();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_main, fragmento)
.commit();
} else if (id == R.id.contacto) {
String emailAdress[] = {"gastondelacruz#gmail.com"};
Intent email= new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,emailAdress);
email.putExtra(Intent.EXTRA_SUBJECT,"Pon aqui el motivo de tu mail");
email.setType("text/plain");
email.putExtra(Intent.EXTRA_TEXT,"Su mensaje");
startActivity(email);
} else if (id == R.id.compartir) {
String texto="https://www.google.com.ar/?gfe_rd=cr&ei=9JuBVvmcGanX8gejsK_4CA&gws_rd=ssl";
Intent intento= new Intent();
intento.setAction(Intent.ACTION_SEND);
intento.putExtra(Intent.EXTRA_TEXT, texto);
intento.setType("text/plain");
startActivity(intento);
} else if (id == R.id.version) {
String prueba="aceptar";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("prueba") //
.setMessage("Esta es una prueba todavia no poseo el numero de version del producto") //
.setPositiveButton(prueba, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO
dialog.dismiss();
}
}); //
builder.show();
} else if (id == R.id.salir) {
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
drawer layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".DrawerPrincipal"
tools:showIn="#layout/app_bar_drawer_principal">
<LinearLayout
android:id="#+id/content_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"></LinearLayout>
</RelativeLayout>
when a object its selected i called the method from the fragment like the following:
DrawerPrincipal prueba=new DrawerPrincipal();
prueba.cambiarFragmento();

This post is old but i'll respond anyway..
It's not immediately obvious what's wrong. Might be helpful if you posted the stack trace of the IllegalStateException.
Things to check:
make sure you're not mixing support fragments/activities with their alternate versions.
Also, you mention navigating from a drawer but the code is adding buttons to the action bar menu. Not sure if this is what you're going for but those are different ui components.

Related

Getting ERROR: When im clickingone of my item in my Recyclerview

I want to make a theme app and I have a home page where I am trying to show some theme As a category, and there I am using RecyclerView for each category, and my Recyclerview get data from firebase real-time database where I use one image link, one text, and one URL which I want to show in my WebView through this code
Intent intent = new Intent(v.getContext().getApplicationContext(), BrowserActivity.class);
intent.putExtra("url_E", url);
v.getContext().startActivity(intent);
but the problem is all items are fetching perfectly from firebase, and showing the correct title and image each and every item of my Recyclerview but if I click the 6 or 7 items from Recyclerview then the link was not loaded correctly, The link that is loading is not that item link, The link is being replaced with another item link and that wrong link I can find in the database from another item in the same category.
****Please Help Me
If I add a Toast.makeText(, url, Toast.LENGTH_SHORT).show(); with setOnClickListener then the correct link is showing in Toast but the load link on the webpage is wrong same!!!! -- -- 🤦‍♀️🤦‍♂️🤦‍♂️🤦‍♂️🤦‍♂️
HErer is my activity :
enter image description here
layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="end"
android:orientation="horizontal">
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:layout_gravity="bottom"
android:layout_marginStart="5dp"
android:layout_marginEnd="10sp"
android:src="#drawable/theme_review" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RVModern"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="8dp"
android:paddingStart="10dp" />
MainFragemnt:
DataRef = FirebaseDatabase.getInstance().getReference("ThemeByStyle");
// Modern
DataRef.child("ModernTheme").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) {
ListDataMODERN = npsnapshot.getValue(ListData.class);
listData1.add(ListDataMODERN);
}
homeAdapter = new HomeAdapter(listData1);
RVModern.setAdapter(homeAdapter);
Collections.reverse(listData1);
RVModern.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
homeAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter:
{
private final List<ListData> listData;
CardView ClickItem;
String url;
ImageView post_img;
TextView post_title;
Dialog OkBox;
public HomeAdapter (List<ListData> listData) {
this.listData = listData;
}
#SuppressLint("WrongConstant")
#NonNull
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_body_home,parent,false);
ClickItem = view.findViewById(R.id.cardview);
OkBox = new Dialog(view.getContext());
return new HomeAdapter.ViewHolder(view);
}/**************************************************************************/
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListData listdata = listData.get(position);
holder.setUrlss(listdata.getUrls());
holder.setTitle(listdata.getTitle());
holder.setImgOne(listdata.getImg1());
// url = listdata.getUrls();
}
#Override
public int getItemCount () {
return listData.size();
// return 2;
}
public class ViewHolder extends RecyclerView.ViewHolder {
View vv;
public ViewHolder(View itemView) {
super(itemView);
vv = itemView;
}
public void setTitle(String title) {
post_title = vv.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setImgOne(String imgone) {
post_img = vv.findViewById(R.id.imgOne);
Glide
.with(vv)
.load(imgone)
.into(post_img);
}
public void setUrlss (String setUrls) {
TextView urltxt = vv.findViewById(R.id.urltxt);
urltxt.setText(setUrls);
url = setUrls;
ClickItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext().getApplicationContext(), BrowserActivity.class);
intent.putExtra("url_E", url);
v.getContext().startActivity(intent);
/* Okbox();
ClipboardManager clipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", setUrlXX);
clipboard.setPrimaryClip(clip);
Toast.makeText(v.getContext().getApplicationContext(), setUrlXX, Toast.LENGTH_SHORT).show();*/
}
});
}
}
private void Okbox() {
OkBox.setContentView(R.layout.ok);
Window window = OkBox.getWindow();
window.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.TOP);
TextView t0title = OkBox.findViewById(R.id.t0title);
t0title.setText(url);
OkBox.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
OkBox.show();
}
}
HELP ME PLZ PLZ PLZ PLZ PLZ PLZ PLZ PLZ

Logout from Navigation Drawer

I would like to create a logout alert dialog from my applications navigation drawer. All the other items in the nav drawer are fragments and I would like for this item to just show an alert dialog
Navigation Drawer
I previously had a button in my MainActivity that used an on click listener and firebase.getInstance.signOut() to take the user back to the login activity:
Previous button on click listener
//on click listener for logout
/*btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
}
});*/
After some redesign I created a navigation drawer that utilizes fragments and i would like when the user selects logout to be prompted with an alert dialog asking are they sure , then for the button to act just how my previous one did and send the user back to the login activity.
I dont see the need of creating another fragment to logout but, correct me if I'm wrong.
Mainactivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.
OnNavigationItemSelectedListener,MainFragment.onFragmentBtnSelected{
public TextView verifyMsg;
public Button btnLogout, verifyEmailBtn;
FirebaseAuth fauth;
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
public NavigationView navigationView;
AlertDialog.Builder reset_alert;
LayoutInflater inflater;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//xml map to java
//btnLogout = findViewById(R.id.btnLogout);
verifyMsg = findViewById(R.id.verifyEmailMsg);
verifyEmailBtn = findViewById(R.id.btnVerifyEmail);
fauth = FirebaseAuth.getInstance();
reset_alert = new AlertDialog.Builder(this);
inflater =this.getLayoutInflater();
//new stuff
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new
ActionBarDrawerToggle(this, drawerLayout,
toolbar, R.string.nav_open, R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
//fragment manager - creates instance of a fragment
//load default fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container_fragment,new MainFragment());
fragmentTransaction.commit();
//if the user email is not verified still show verify msg
if(!fauth.getCurrentUser().isEmailVerified()){
verifyEmailBtn.setVisibility(View.VISIBLE);
verifyMsg.setVisibility(View.VISIBLE);
}
//on click listener for verify email button
verifyEmailBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//send verification email
fauth.getCurrentUser().sendEmailVerification()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this,"Verification Sent",Toast.LENGTH_SHORT).show();
verifyEmailBtn.setVisibility(View.GONE);
verifyMsg.setVisibility(View.GONE);
}
});
}
});
}
//able to select the items in nav drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//auto close drawer
drawerLayout.closeDrawer(GravityCompat.START);
//Fragment fragment;
int mId = item.getItemId();
}
if (mId == R.id.homeItem){
//load default fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment,new MainFragment());
fragmentTransaction.commit();
}
if (mId == R.id.profileSettings){
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment,new ProfileFragment());
fragmentTransaction.commit();
}
if (mId == R.id.logoutItem){
}
return true;
}
#Override
public void onBtnSelected() {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment,new ProfileFragment());
fragmentTransaction.commit();
} }
MainFragment.java
public class MainFragment extends Fragment {
private onFragmentBtnSelected listener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main,container,false);
Button clickme = view.findViewById(R.id.clickHF);
clickme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onBtnSelected();
}
});
return view;
}
#Override
public void onAttach(#NonNull Context context){
super.onAttach(context);
if(context instanceof onFragmentBtnSelected ){
listener =(onFragmentBtnSelected) context;
}
else {
throw new ClassCastException(context.toString() + " must implement listiner");
}
}
public interface onFragmentBtnSelected{
public void onBtnSelected();
}
}
nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:title="General">
<menu>
<item
android:id="#+id/homeItem"
android:icon="#drawable/ic_baseline_home_24"
android:title="#string/Home" />
</menu>
</item>
<item android:title="Account Settings">
<menu>
<item
android:id="#+id/profileSettings"
android:icon="#drawable/ic_baseline_account_circle_24"
android:title="Profile" />
</menu>
</item>
<item android:title="App Features">
<menu>
<item
android:id="#+id/logoutItem"
android:icon="#drawable/ic_baseline_power_settings_new_24"
android:title="#string/logout" />
</menu>
</item></menu>
Any help would be greatly appreatiated , having trouble best utilizing fragments in a navigation drawer
Mainactivity.java:
onNavigationItemSelected method inside this
without Alert Dialog
if (mId == R.id.logoutItem){
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
}
with Alert Dialog use
if (mId == R.id.logoutItem){
MaterialAlertDialogBuilder(this)
.setTitle("Title")
.setMessage("Message")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Ok") { _, _ ->
FirebaseAuth.getInstance().signOut();
startActivity(new
Intent(getApplicationContext(),LoginActivity.class));
finish();
}
.setNegativeButton("Cancel") { _, _ ->
Toast.makeText(this, "clicked Cancel", Toast.LENGTH_LONG).show()
}
.show()
}

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 transfer variables to a fragment was created using the ActionBarActivity?

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];
}

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