I am trying to build a Translucent Navigation bar for my android app. I separately tried developing the task bar and then had intend to include it in my application.
I am not allowed to upload images yet (as I don't have the reputation), therefore here's an example of what I am trying to build for my APP:
Image Slider example
I am getting errors in the MainActivity.java file.
I get an Error in the following line of code :
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close)
Error :
Error:(48, 79) error: cannot find symbol variable navigation_drawer_open
Error:(48, 112) error: cannot find symbol variable navigation_drawer_close
This is the entire code of MainActivity.java file:
package sha.testing_sidebar;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
String TITLES [] = {"Home","Events","Mail","Blog","Attending"};
int ICONS [] = {R.drawable.ic_home,R.drawable.ericsson_2_png,R.drawable.ic_mqil_hdpi,R.drawable.ic_blog_2,R.drawable.ic_attending};
String NAME = "Sharang Bharadwaj";
String EMAIL = "sha.bh91#gmail.com";
int PROFILE = R.drawable.sha1;
private Toolbar toolbar;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
DrawerLayout Drawer;
ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
mAdapter = new sha.testing_sidebar.MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//actions upon opening slider
//presently nothing
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
//actions upon closing slider
//presently nothing
}
};
//Drawer Toggle Object made
Drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The error is
Add the following in your strings.xml file
<string name="navigation_drawer_open">Drawer Open</string>
<string name="navigation_drawer_close">Drawer Closed</string>
It should work after that.
Just copy/paste this in the strings file
<string name="navigation_drawer_open">Drawer Open</string>
<string name="navigation_drawer_close">Drawer Closed</string>
they might be there already, if true, both will be underlined in red.
if so erase the existing ones and copy/paste the same two lines.
Related
I used the basic "Navigation Drawer Acticity" in Anroid Studio when creating the new project. The fragments work well and I've managed to add new fragments and everything.
However, items in the drawer menu that direct you to a certain website don't work. I've tried different methods with public boolean onNavigationItemSelected(MenuItem item){} and nothing happens when I press the items.
It looks like this:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
As you can see I did nothing for the fragments to work since they work fine already but when I press the button "moodle", nothing happens.
What have I done wrong?
Here is my MainActivity:
package com.example.ustudy;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.Toast;
import com.example.ustudy.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.ustudy.databinding.ActivityMainBinding;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//required for the top bar to be clickable
setSupportActionBar(binding.appBarMain.toolbar);
//button in the bottom right corner
binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
//Navigationview for the drawer (implemented in "activity_main.xml")
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
//each screen mentioned in the columns below (R.id.xy) will show the hamburger menu in the top left corner
//on screens, not included in the columns, there will be a "back arrow" instead of the ham. menu
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_nachricht, R.id.nav_lerngruppe, R.id.nav_lehrveranstaltung)
.setDrawerLayout(drawer)
.build();
//controls what happens when one of the items in the hamburger menu is clicked on
//go to "mobile_navigation.xml" to add screens to go to
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
//required to set up the hamburger menu icon and the back-arrow icon on the top bar(without it
//the user had to slide the side of the screen to open the menu)
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
//enables the items in the hamburger menu to go to a certain screen after clicking on them
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu (three dots on the right); this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
//enables the usage of the back-arrow on every screen
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull #NotNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
}
Please, let me know if you need more!
I am creating a small app that will allow the user to view different categories of books for college.
So far in the activity main drawer I have a few different categories that should load a layout with a listView and populate this list from an arrayAdapter when selected. I have it set up and semi-working on one of my layouts, but the problem arises when I change to a different category from the navigation drawer, the listView is still displayed on the screen and I can't seem to figure out how to get it to stop.
I thought that I would need to use endTransaction() but I'm not really sure yet if I'm using the right thing.
I am a beginner to Java and Android Studio, so I hope that I am making sense in what I am asking.
If more code or information is needed, I will be happy to provide.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.ViewGroup;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
//loads the home screen when app launches
displaySelectedScreen(R.id.nav_home);
}
#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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int id) {
Fragment fragment = null;
//loads each layout inflator depending on what menu item has been clicked
switch(id) {
case R.id.nav_home:
fragment = new Home();
break;
case R.id.nav_book:
fragment = new All();
break;
case R.id.nav_sci_fi:
fragment = new SciFi();
break;
case R.id.nav_fantasy:
fragment = new Fantasy();
break;
case R.id.nav_dystopian:
fragment = new Dystopian();
break;
case R.id.nav_about:
fragment = new About();
break;
case R.id.nav_contact:
fragment = new ContactUs();
break;
}
if(fragment != null) {
FragmentTransaction ft = getSupportFragmentManager(). beginTransaction();
ft.replace(R.id.content_main, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
FragmentManager fm=getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_book) {
// Handle the camera action
} else if (id == R.id.nav_sci_fi) {
fm .beginTransaction().replace(R.id.content_frame, new BookFragment()).commit(); setTitle("Sci-Fi");
//TODO: endTransaction
} else if (id == R.id.nav_fantasy) {
} else if (id == R.id.nav_dystopian) {
} else if (id == R.id.nav_about) {
}
displaySelectedScreen(id);
return true;
}
}
Your displaySelectedScreen() function is using a FragmentTransaction instead of FragmentManager. Try using FragmentManager.
package com.maya.helloandroid;
import java.util.ArrayList;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.maya.helloandroid.adapter.NavDrawerListAdapter;
import com.maya.helloandroid.model.NavDrawerItem;
#SuppressWarnings("deprecation")
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles=
getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0],
navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],
navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2],
navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3],
navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4],
navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5],
navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for
accessibility
R.string.app_name // nav drawer close - description for
accessibility
){
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
/*if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has
occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
my style.xml contains:
style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar"
my android manifest contains:
android:minSdkVersion="14"
android:targetSdkVersion="21"
by the above circumstances, my app unfortunately stopped and I got this error:
08-17 12:23:58.069: E/AndroidRuntime(15535): Caused by: java.lang.NullPointerException 08-17 12:23:58.069: E/AndroidRuntime(15535): at com.maya.helloandroid.MainActivity.onCreate(MainActivity.java:85)
on this line:
getActionBar().setDisplayHomeAsUpEnabled(true);
please help me to solve this problem.
Avoid Activity use AppcompatActivity or ActionBarActivity instead of Activity .
follow here may be your problem can fix .
getActionBar().setDisplayHomeAsUpEnabled(true); throws NullPointerException on new activity creation (Google - Basic Tutorial)
getActionBar().setDisplayHomeAsUpEnabled(true) throws NullPointerException
I created a blank app with just an ad and it force closes when it loads. Heres what i did:
added the google-play-services library to the project
inserted the meta-data tag
inserted the permissions tag
inserted the activity tag
inserted the xmlns line and com.google tag in the fragment xml
imported com.google... into the main java
added the adview code into the main java
saved it.
There are zero errors and the graphical display shows a box that says "ads by google" but doesnt show ads. When i try to run it in an emulator, the app force closes. Did i miss something? Thanks guys!
package com.example.abc;
import com.google.android.gms.ads.*;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.build();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Ok thanks the link works and I have looked at the code.
I have edited your question to include the code.
Could you try it this way please:
And instead of simply importing import com.google.android.gms.ads.*;
Try using:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adView = new AdView(this); //I couldn't see this line in your code. It goes under the line setContentView(R.layout.activity_main);
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
adView.loadAd(adRequest);
And let me know what happens. Also how do you have the ads setup in your XML?
I am new to android studio and I am reading the tutorials on i-programmer located here (http://www.i-programmer.info/programming/android/5914-android-adventures-activity-and-ui.html?start=2)
The two objects in the environment are a button and a large text widget instanced
in android studio's xml designer.
The problem: A method for setting text referenced in the tutorial is showing this error message when I try to run the code: error: cannot find symbol method setText(String)
And this error shows up in the text editor: Cannot resolve method 'setText(java.lang.String)'
Provided Source Code:
package com.example.helloworld1.helloworld1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonClick(View v){
Button button=(Button) v;
v.setText("I've Been Clicked!"); // This is where the error happens
}
}
I think you meant to use button instead of v.
button.setText("I've Been Clicked!");