i have create a webapp using webview. Here in this i have a left sidedrawer with different links opening in same web view. Problem i am facing is as soon as i click on any of the option in drawer that web views is open and it gets reload again and again. here i am pasting the xml and java code my application.
MAIN ACTIVITY FILE
package com.example.dr.app3;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
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.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
//import java.net.URI;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
// intialize web view
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
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 = (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);
//webview control content
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve WebProformance
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//load cahe resources if requried otherwise load from network
webView.getSettings().setAppCacheEnabled(true);//enable catch
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//makes all coloms no wider then screen
webSettings.setUseWideViewPort(true);//
webSettings.setSavePassword(true);//save username password
webSettings.setSaveFormData(true);//save date and time
webSettings.setEnableSmoothTransition(true);// smooth transition
webView.loadUrl("http://school.techjunctionplace.in");
//Force webview to open link in itself
webView.setWebViewClient(new MyWebViewClient());
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.dashboard) {
// Handle the camera action
webView.loadUrl("http://www.school.techjunctionplace.in/#/");
} else if (id == R.id.message) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/messages");
} else if (id == R.id.calender) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/calender");
} else if (id == R.id.classes_schedule) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/classschedule");
} else if (id == R.id.attendance) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/attendance");
} else if (id == R.id.attendance_stats) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/attendanceStats");
}else if (id == R.id.staff) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/staffAttendance");
}else if (id == R.id.hostel) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/hostel");
}else if (id == R.id.hostel_category) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/hostelCat");
}else if (id == R.id.library) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/library");
}else if (id == R.id.media_center) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/media");
}else if (id == R.id.teachers) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/teachers");
}else if (id == R.id.students) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/students");
}else if (id == R.id.parents) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/parents");
}else if (id == R.id.grade_level) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/gradeLevels");
}else if (id == R.id.study_material) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/materials");
}else if (id == R.id.assignments) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/assignments");
}else if (id == R.id.exam_list) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/examsList");
}else if (id == R.id.online_exams) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/onlineExams");
}else if (id == R.id.news_board) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/newsboard");
}else if (id == R.id.events) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/events");
}else if (id == R.id.fee_types) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/feeType");
}else if (id == R.id.fee_allocation) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/feeAllocation");
}else if (id == R.id.payments) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/payments");
}else if (id == R.id.expenses) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/expenses");
}else if (id == R.id.transportation) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/transports");
}else if (id == R.id.classes) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/classes");
}else if (id == R.id.sections) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/sections");
}else if (id == R.id.subjects) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/subjects");
}else if (id == R.id.reports) {
webView.loadUrl("http://www.school.techjunctionplace.in/#/reports");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.school.techjunctionplace.in")) {
// open url content in web view
return false;
}
// here open external url in browser
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
//ProgressDialogue
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd=new ProgressDialog(MainActivity.this);
pd.setTitle("Please Wait..");
pd.setMessage("It's Loading..");
pd.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
super.onPageFinished(view, url);
}
}
//goto previous page on back button
#Override
public boolean onKeyDown(int keycode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keycode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keycode, event);
}}
XML FILE OF SIDE DRAWER
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/dashboard"
android:icon="#drawable/ic_menu_camera"
android:title="Dashboard" />
<item
android:id="#+id/message"
android:icon="#drawable/ic_menu_gallery"
android:title="Messages" />
<item
android:id="#+id/calender"
android:icon="#drawable/ic_menu_slideshow"
android:title="Calender" />
<item
android:id="#+id/classes_schedule"
android:icon="#drawable/ic_menu_manage"
android:title="Classes Schedule" />
</group>
<item android:title="Attendance">
<menu>
<item
android:id="#+id/attendance"
android:icon="#drawable/ic_menu_share"
android:title="Attendance" />
<item
android:id="#+id/attendance_stats"
android:icon="#drawable/ic_menu_send"
android:title="Attendance Stats" />
<item
android:id="#+id/staff"
android:icon="#drawable/ic_menu_camera"
android:title="Staff Attendance" />
</menu>
</item>
<item android:title="Hostel Management">
<menu>
<item
android:id="#+id/hostel"
android:icon="#drawable/ic_menu_share"
android:title="Hostel" />
<item
android:id="#+id/hostel_category"
android:icon="#drawable/ic_menu_send"
android:title="Hostel Category" />
</menu>
</item>
<item android:title="School Info">
<menu>
<item
android:id="#+id/library"
android:icon="#drawable/ic_menu_camera"
android:title="Library" />
<item
android:id="#+id/media_center"
android:icon="#drawable/ic_menu_gallery"
android:title="Media Center" />
<item
android:id="#+id/teachers"
android:icon="#drawable/ic_menu_slideshow"
android:title="Teachers" />
<item
android:id="#+id/students"
android:icon="#drawable/ic_menu_manage"
android:title="Students" />
<item
android:id="#+id/parents"
android:icon="#drawable/ic_menu_manage"
android:title="Parents" />
<item
android:id="#+id/grade_level"
android:icon="#drawable/ic_menu_manage"
android:title="Grade Level" />
<item
android:id="#+id/study_material"
android:icon="#drawable/ic_menu_manage"
android:title="Study Material" />
<item
android:id="#+id/assignments"
android:icon="#drawable/ic_menu_manage"
android:title="Assigenments" />
<item
android:id="#+id/exam_list"
android:icon="#drawable/ic_menu_manage"
android:title="Exam List" />
<item
android:id="#+id/online_exams"
android:icon="#drawable/ic_menu_manage"
android:title="Online Exams" />
<item
android:id="#+id/news_board"
android:icon="#drawable/ic_menu_manage"
android:title="News Board" />
<item
android:id="#+id/events"
android:icon="#drawable/ic_menu_manage"
android:title="Events" />
</menu>
</item>
<item android:title="Accounting">
<menu>
<item
android:id="#+id/fee_types"
android:icon="#drawable/ic_menu_share"
android:title="Fee Types" />
<item
android:id="#+id/fee_allocation"
android:icon="#drawable/ic_menu_send"
android:title="Fee Allocation" />
<item
android:id="#+id/payments"
android:icon="#drawable/ic_menu_send"
android:title="Payments" />
<item
android:id="#+id/expenses"
android:icon="#drawable/ic_menu_send"
android:title="Expenses" />
</menu>
</item>
<item android:title="Transportation">
<menu>
<item
android:id="#+id/transportation"
android:icon="#drawable/ic_menu_camera"
android:title="Transportation" />
</menu>
</item>
<item android:title="Classes">
<menu>
<item
android:id="#+id/classes"
android:icon="#drawable/ic_menu_share"
android:title="Classes" />
<item
android:id="#+id/sections"
android:icon="#drawable/ic_menu_send"
android:title="Sections" />
</menu>
</item>
<item android:title="Reports">
<menu>
<item
android:id="#+id/subjects"
android:icon="#drawable/ic_menu_share"
android:title="Subjects" />
<item
android:id="#+id/reports"
android:icon="#drawable/ic_menu_send"
android:title="Reports" />
</menu>
</item>
In above code even
Uri.parse(url).getHost().equals("www.school.techjunctionplace.in"))
is also not working.
I am a beginner in android please help to identify what is the actual problem in my code.
in the onCreate method:
webView.loadUrl("http://school.techjunctionplace.in");
replace it with
webView.loadUrl("http://www.school.techjunctionplace.in");
Some changes in the webview client:
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().contains("www.school.techjunctionplace.in")) {
// open url content in web view
return false;
}
// here open external url in browser
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
//ProgressDialogue
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if(pd == null) {
pd = new ProgressDialog(HomeActivity.this);
pd.setTitle("Please Wait..");
pd.setMessage("It's Loading..");
pd.show();
}
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
if(pd != null && pd.isShowing())
pd.dismiss();
pd = null;
super.onPageFinished(view, url);
}
}
Related
This is my code:
package pi.com.pariwisata;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
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.MenuItem;
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);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_maps) {
Intent peta = new Intent(this, MapsActivity.class);
startActivity(peta);
} else if (id == R.id.nav_list) {
Intent list = new Intent(this, ListActivity.class);
startActivity(list);
} else if (id == R.id.nav_about) {
Intent tentang = new Intent(this, TentangActivity.class);
startActivity(tentang);
} else if (id == R.id.nav_exit) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Keluar Dari Aplikasi?")
.setCancelable(false)//tidak bisa tekan tombol back
//jika pilih yess
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
//jika pilih no
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and I have an error in setSupportActionBar(toolbar);
can you help me?
Try setting your Activity's parent theme to Theme.AppCompat.Light.NoActionBar
The important part is "NoActionBar"
Then you can use your custom ToolBar at your layout.
Set windowNoTitle and 'windowActionBar` in base theme of styles.xml and apply this theme to your application in AndroidManifest.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
I am currently working on an app that i implemented a toolbar and a search functionality on the toolbar with a searchview to filter list views which is working fine.
I also have a navigation drawer whereby i also want one of its items to do exactly what the search functionality is doing on the toolbar. How do implement an intent to lead me to SearchViewon toolbar when searchitem is clicked from navigation drawer.
menu_main for toolbar
<menu 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"
tools:context=".MainActivity">
<item
android:id="#+id/viewMode"
android:orderInCategory="100"
app:showAsAction="never"
android:icon="#drawable/ic_view_compact_black_24dp"
android:title="#string/view" />
<item
// my search functionality
android:id="#+id/search"
android:orderInCategory="100"
app:actionViewClass= "android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"
android:icon="#drawable/ic_search"
android:title="#string/search" />
</menu>
activity_navdrawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_notes"
android:icon="#drawable/ic_note_add_black_24dp"
android:title="#string/first_layout" />
<item
// search functionality which should lead me to searchview on toolbar
android:id="#+id/nav_search"
android:icon="#drawable/ic_search_black_24dp"
android:title="#string/third_layout" />
</group>
<item android:title="#string/app_communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_share_black_24dp"
android:title="#string/app_share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_email_black_24dp"
android:title="#string/app_send" />
</menu>
</item>
</menu>
from main activity
public boolean onNavigationItemSelected(MenuItem item) {
// Handling navigation view item clicks here.
int id = item.getItemId();
if(id == R.id.nav_notes) {
Intent noteIntent = new Intent(this, MainActivity.class);
startActivity(noteIntent);
} else if(id == R.id.nav_search) {
MenuItem searchMenuItem = mOptionsMenu.findItem(R.id.search);
searchMenuItem.expandActionView();
// what should i implement here?
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(`final` Menu menu) {
mOptionsMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayAdapter<Note> arrayAdapter = (ArrayAdapter<Note>) mListNotes.getAdapter();
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
Try the following code below:
private Menu mOptionsMenu;
...
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
mOptionsMenu = menu;
...
}
...
public boolean onNavigationItemSelected(MenuItem item) {
...
} else if(id == R.id.nav_search) {
MenuItem searchMenuItem = mOptionsMenu.findItem(R.id.menu_search);
searchMenuItem.expandActionView();
}
...
Add <category android:name="android.intent.category.DEFAULT" /> to your search activity in manifest. Then do this:
else if(id == R.id.nav_search) {
startActivity(new Intent(Intent.ACTION_SEARCH));
}
If this works, courtesy - Start Activity Using Custom Action
I'm trying to use a navigation drawer in my Main activity.
when i run it in API 23 Emulator , everything looks fine.
But when I run it in API 16 Emulator, my action bar goes away!
Here is my manifest file :
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Here is my styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/line1</item>
<item name="colorPrimaryDark">#color/line1_dark</item>
<item name="colorAccent">#color/isbc</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Here is my v21/styles.xml
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
</style>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/line1</item>
<item name="colorPrimaryDark">#color/line1_dark</item>
<item name="colorAccent">#color/isbc</item>
</style>
And this is my Mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
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 = (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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
changeTypeface(navigationView);
}
#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;
}
private void applyFontToItem(MenuItem item, Typeface font) {
SpannableString mNewTitle = new SpannableString(item.getTitle());
mNewTitle.setSpan(new CustomTypefaceSpan("", font, 16), 0 ,
mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
item.setTitle(mNewTitle);
}
private void changeTypeface(NavigationView navigationView) {
FontTypeface fontTypeface = new FontTypeface(this);
Typeface typeface = fontTypeface.getTypefaceAndroid();
MenuItem item;
item = navigationView.getMenu().findItem(R.id.nav_camera);
item.setTitle("لیست ایستگاه ها");
item.setIcon(R.drawable.ic_action_stations);
applyFontToItem(item, typeface);
item = navigationView.getMenu().findItem(R.id.nav_gallery);
item.setTitle("نقشه");
item.setIcon(R.drawable.ic_action_map);
applyFontToItem(item, typeface);
item = navigationView.getMenu().findItem(R.id.nav_slideshow);
item.setTitle("درباره ما");
item.setIcon(R.drawable.ic_action_us);
applyFontToItem(item, typeface);
}
#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.nav_camera) {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit(); }
else if (id == R.id.nav_gallery) {
MapFragment fragment = new MapFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my app_bar_main :
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/fragment_main" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
Here is my activity_main.xml
<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:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
When I run this code in emulator API 21, everything looks fine.
But when I run it in API 16, i get this error:
"This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead."
I guess it's telling me not to use actionbar, but how can i actually display my navigation drawer if i set windowActionBar to false?
i've tried this topic but it didn't work
I am having problems implementing the actionbar (which I think is now replaced by toolbar). What I want is a small drop down menu with the 3 dots where I can have a few options such as settings and credits. I have tried to set it up so that the menu appears on the homelistview.java page. I feel like I have been going in circles trying different solutions and getting a new error each time and it always points back to the same location mentioned below.
setSupportActionBar(toolbar);
I had originally thought it was because I didn't include setContentView(R.layout.activity_main); but it was not happy including 2 content views. Any help would be appreciated.
Here is my code.
styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
--------------- menu_main.xml-------------------
<menu 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"
tools:context="cs495capstone.edu.bsu.myapplication.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_credits"
android:orderInCategory="100"
android:title="#string/action_credits"
app:showAsAction="never" />
<item
android:id="#+id/action_lovely"
android:orderInCategory="100"
android:title="#string/action_lovely"
app:showAsAction="never" />
</menu>
--------------activity_main.xml ----------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
tools:context="cs495capstone.edu.bsu.myapplication.HomeActivityListview">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/activity_add_appointment" />
<include layout="#layout/activity_add_history" />
<include layout="#layout/activity_appointments" />
<include layout="#layout/activity_dog_profile" />
<include layout="#layout/activity_history" />
<include layout="#layout/activity_home" />
<include layout="#layout/activity_home_activity_listview" />
<include layout="#layout/activity_login" />
<include layout="#layout/activity_new_dog" />
<include layout="#layout/activity_registration" />
<include layout="#layout/activity_splash_screen" />
<include layout="#layout/activity_update_dog" />
</android.support.design.widget.CoordinatorLayout>
----------------------- homeactivitylistview.xml-------------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
#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);
}
public void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
------------------ main_activity.java -----------------
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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);
}
}
--------------homelistview.java------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
#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);
}
public void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
---------------androidmanifest-----------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cs495capstone.edu.bsu.doggydid" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".SplashScreenActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RegistrationActivity"
android:label="Registration" />
<activity
android:name=".NewDogActivity"
android:label="Dog Information" />
<activity
android:name=".LoginActivity"
android:label="Login" />
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" />
<activity
android:name=".DogProfileActivity"
android:label="#string/title_activity_dog_profile" />
<activity
android:name=".HistoryActivity"
android:label="#string/title_activity_records" />
<activity
android:name=".addHistoryActivity"
android:label="#string/title_activity_add_record" />
<activity
android:name=".EventsActivity"
android:label="#string/title_activity_events" />
<activity
android:name=".addEventsActivity"
android:label="#string/title_activity_add_events" />
<activity
android:name=".UpdateDogActivity"
android:label="#string/title_activity_update_dog" />
<activity
android:name=".HomeActivityListview"
android:label="#string/title_activity_home_activity_listview"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
-----------------------Error Readout--------------------
04-14 13:35:36.905 3117-3117/cs495capstone.edu.bsu.doggydid E/AndroidRuntime: FATAL EXCEPTION: main
Process: cs495capstone.edu.bsu.doggydid, PID: 3117
java.lang.RuntimeException: Unable to start activity ComponentInfo{cs495capstone.edu.bsu.doggydid/cs495capstone.edu.bsu.doggydid.HomeActivityListview}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
at android.support.v7.widget.ToolbarWidgetWrapper.(ToolbarWidgetWrapper.java:98)
at android.support.v7.widget.ToolbarWidgetWrapper.(ToolbarWidgetWrapper.java:91)
at android.support.v7.app.ToolbarActionBar.(ToolbarActionBar.java:73)
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:205)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at cs495capstone.edu.bsu.doggydid.HomeActivityListview.onCreate(HomeActivityListview.java:31)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Your Toolbar toolbar is declared/ initialized in the onCreate only, hence the scope is gone out of that method...
define the object as an activity variable and initialize it in the onCreate
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
private Toolbar toolbar; //define it here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
toolbar = (Toolbar) findViewById(R.id.toolbar); //but init here
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
I cant seem to get my code to work. I keep getting a error.
I made a selector.xml with this code
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="#drawable/loginbuttondn" />
<item android:state_selected="false"
android:drawable="#drawable/loginbutton" />
</selector>
heres my actual code
package monaiz.net.periscope.periscope;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
public class MainActivity extends AppCompatActivity implements OnTouchListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
v.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
v.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
return true;
}
});
}
return true;
}
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);
}
}
Im trying to get it so that when i click the button it has a click down effect showing the other image
Im getting a error here:
Im still getting a error on this line v.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
on the "v."
code for my button
<ImageView
android:layout_width="280dp"
android:layout_height="90dp"
android:layout_marginTop="830px"
android:layout_marginLeft="55dp"
android:src="#drawable/loginbutton"/>
Your selector needs to look like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#drawable/loginbuttondn" />
<item android:drawable="#drawable/loginbutton" />
</selector>
Call this login_button_selector.xml and put it in your /res/drawable folder
Now use it like this:
<ImageView
android:layout_width="280dp"
android:layout_height="90dp"
android:layout_marginTop="830px"
android:layout_marginLeft="55dp"
android:src="#drawable/login_button_selector"/>
When the view is in "pressed" state, it will match the first item in the selector. When it is not in "pressed" state, it will just match the second item in the selector.
Use state_pressed:
drawable/selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#drawable/loginbuttondn" />
<item
android:drawable="#drawable/loginbutton" />
</selector>
<Button
android:layout_width="280dp"
android:layout_height="90dp"
android:background="#drawable/selector"/>