I am working on an OCR app with a Surface View and Google Vision API, which works fin; but the Surface View extends over the whole Display of the Device (Galaxy Grand Prime). It should only have half of the size or less, so that the recognised text can be displayed in a Text View beneath the Surface View. Although I googled a lot, I couldn´t solve this problem and would appreciate any support and advice, thanks!
The Main Activity:
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
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.Button;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SurfaceView mCameraView;
TextView mTextView;
CameraSource mCameraSource;
private static final String TAG = "MainActivity";
private static final int requestPermissionID = 101;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
mCameraView = findViewById(R.id.surfaceView);
mTextView = findViewById(R.id.text_view);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
startCameraSource();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode != requestPermissionID) {
Log.d(TAG, "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
mCameraSource.start(mCameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void startCameraSource() {
//Create the TextRecognizer
final TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.w(TAG, "Detector dependencies not loaded yet");
} else {
//Initialize camerasource to use high resolution and set Autofocus on.
mCameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.setRequestedFps(2.0f)
.build();
/**
* Add call back to SurfaceView and check if camera permission is granted.
* If permission is granted we can start our cameraSource and pass it to surfaceView
*/
mCameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
requestPermissionID);
return;
}
mCameraSource.start(mCameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCameraSource.stop();
}
});
//Set the TextRecognizer's Processor.
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
/**
* Detect all the text from camera using TextBlock and the values into a stringBuilder
* which will then be set to the textView.
* */
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items = detections.getDetectedItems();
if (items.size() != 0 ){
mTextView.post(new Runnable() {
#Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for(int i=0;i<items.size();i++){
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
mTextView.setText(stringBuilder.toString());
// Start NewActivity.class
String recognizedText = mTextView.getText().toString();
Intent i = new Intent(MainActivity.this, ListActivity.class);
i.putExtra("recognized Text", recognizedText);
}
});
}
}
});
}
}
#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.nav_camera) {
String recognizedText = mTextView.getText().toString();
Intent i = new Intent(MainActivity.this, ListActivity.class);
i.putExtra("recognized Text", recognizedText);
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent" />
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_weight="2"/>
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="8dp"
android:layout_weight="1"
android:gravity="center"
android:textStyle="bold"
android:text="#string/txt_message"
android:textColor="#android:color/black"
android:textSize="20sp" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Related
I have been trying to figure this out but it's been a disaster.
I have this menu which populates and I can't change the background or I can't add menu icons to it. can someone help me to figure this out please..!
this is my main activity.xml
<LinearLayout
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:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?android:attr/actionBarSize" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white" />
<com.vproductions.xinxilanka.views.DrawerNavigationListView
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
this is the mainactivity.java
package com.vproductions.xinxilanka.activities;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.vproductions.xinxilanka.utils.EventBus;
import com.squareup.otto.Subscribe;
import com.vproductions.xinxilanka.R;
import com.vproductions.xinxilanka.events.DrawerSectionItemClickedEvent;
import com.vproductions.xinxilanka.fragments.AdvancedSearchFragment;
import com.vproductions.xinxilanka.fragments.NearMapFragment;
import com.vproductions.xinxilanka.fragments.QuickSearchFragment;
import com.vproductions.xinxilanka.repository.FieldRepository;
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private String mCurrentFragmentTitle;
private static Boolean firstInit = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(R.string.drawer_opened);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(R.string.drawer_closed);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (firstInit || getSupportFragmentManager().getFragments() == null)
displayInitialFragment();
firstInit = false;
}
private void displayInitialFragment() {
getSupportFragmentManager().beginTransaction().replace(R.id.container, QuickSearchFragment.getInstance()).commit();
mCurrentFragmentTitle = getString(R.string.section_quick_search);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#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.
if (mActionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
EventBus.getInstance().register(this);
}
#Override
protected void onStop() {
EventBus.getInstance().unregister(this);
super.onStop();
}
#Subscribe
public void onDrawerSectionItemClickEvent(DrawerSectionItemClickedEvent event) {
mDrawerLayout.closeDrawers();
if (event == null || TextUtils.isEmpty(event.section) || event.section.equalsIgnoreCase(mCurrentFragmentTitle)) {
//return;
}
//Toast.makeText(this, "MainActivity: Section Clicked: " + event.section, Toast.LENGTH_SHORT).show();
if (event.section.equalsIgnoreCase(getString(R.string.section_map))) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, NearMapFragment.getInstance()).commit();
} else if (event.section.equalsIgnoreCase(getString(R.string.section_quick_search))) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, QuickSearchFragment.getInstance()).commit();
} else if (event.section.equalsIgnoreCase(getString(R.string.advanced_search))) {
if (FieldRepository.getInstance().getSeted()) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, AdvancedSearchFragment.getInstance()).commit();
} else {
Toast.makeText(this, getString(R.string.fields_not_loaded), Toast.LENGTH_LONG).show();
}
} else if (event.section.equalsIgnoreCase(getString(R.string.add_property))) {
// go to external website
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://xinxilanka.com/index.php/admin/user/login/"));
startActivity(intent);
} else if (event.section.equalsIgnoreCase(getString(R.string.open_website))) {
// go to external website
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(getString(R.string.script_url)));
startActivity(intent);
} else {
return;
}
mCurrentFragmentTitle = event.section;
}
public void open(View view) {
Intent browserIntent = (new Intent(Intent.ACTION_VIEW, Uri.parse("http://xinxilanka.com/index.php/admin/user/login/")));
startActivity(browserIntent);
}
}
the navigation menu that shows now is just white background and no icons.
I want to add a nice header and some icons to the menu items.
this menu is a auto populated menu.
basically the navigation menu which populates menu items without defining them in a menu file.
see below for drawernavigationlistview class
package com.vproductions.xinxilanka.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.vproductions.xinxilanka.R;
import com.vproductions.xinxilanka.adapters.DrawerNavigationListAdapter;
import com.vproductions.xinxilanka.events.DrawerSectionItemClickedEvent;
import com.vproductions.xinxilanka.utils.EventBus;
/**
* Created by sandi on 04.01.2016..
*/
public class DrawerNavigationListView extends ListView implements AdapterView.OnItemClickListener {
public DrawerNavigationListView(Context context) {
this(context, null);
}
public DrawerNavigationListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawerNavigationListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Populate menu
DrawerNavigationListAdapter adapter = new DrawerNavigationListAdapter(getContext(), 0);
adapter.add(getContext().getString(R.string.section_quick_search));
adapter.add(getContext().getString(R.string.section_map));
adapter.add(getContext().getString(R.string.advanced_search));
adapter.add(getContext().getString(R.string.howto_use));
if (getContext().getString(R.string.website_enabled).equalsIgnoreCase("true")) {
adapter.add(getContext().getString(R.string.add_property));
adapter.add(getContext().getString(R.string.open_website));
}
setAdapter(adapter);
setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
//Toast.makeText(getContext(), "SectionClicked: " + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
EventBus.getInstance().post(new DrawerSectionItemClickedEvent((String) parent.getItemAtPosition(position)));
}
}
navigation_drawer_list_item.xml file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/navigation_list_selector"
android:gravity="left"
android:padding="8dp"
android:textSize="14sp"
android:drawableStart="#mipmap/ic_stars_black_24dp"
android:drawableLeft="#mipmap/ic_stars_black_24dp"
android:drawablePadding="3dp"
android:textColor="#color/black">
</TextView>
You have to define the background into the DrawerNavigationListAdapter XML.
I converted a website into an app with WebView in Android Studio. Everything is fine but the youtube videos that was in my website does not go in full Screen. I am a beginner, so please help me in solving this.
Main Activity Code ---
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
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.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import java.net.URI;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private MyWebviewClient mWebChromeClient;
#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
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mwebView.getSettings().setAppCacheEnabled(true);
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mwebView.setWebChromeClient(new MyChromeBrowser());
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
mwebView.loadUrl("https://laughonlyblog.wordpress.com");
//force links open in webview only
}
private class MyChromeBrowser extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
}
}
#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.nav_camera) {
// Handle the camera action
mwebView.loadUrl("http://www.newsweek.com/us");
} else if (id == R.id.nav_slideshow) {
mwebView.loadUrl("http://www.newsweek.com/world");
} else if (id == R.id.nav_manage) {
mwebView.loadUrl("http://www.newsweek.com/tech-science");
} else if (id == R.id.nav_gallery) {
mwebView.loadUrl("http://www.newsweek.com/sports");
} else if (id == R.id.nav_share) {
mwebView.loadUrl("http://www.newsweek.com/about-newsweek");
} else if (id == R.id.nav_send) {
mwebView.loadUrl("http://www.newsweek.com/contact");
}
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.laughonlyblog.wordpress.com/about/")) {
//open url contents in webview
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} */
view.loadUrl(url);
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("Website is 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 when pressing back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebView.canGoBack()) {
mwebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
To achieve this follows these steps :
1) Set WebChromeClient to your webview.
Exmaple : WebView.setWebChromeClient(new MyChromeBrowser());
2) Implement method onShowCustomView() and onHideCustomView() inside your WebChromeClient.
Example : `
private class MyChromeBrowser extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
}
}`
3) Give android:hardwareAccelerated="true" in manifest file for your activity.
Example : <activity android:name=".MainActivity"
android:hardwareAccelerated="true"
/>
Update :
To fix this try these :
change these lines : webView.setWebChromeClient(new MyWebChromeClient()); to
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
inside initWebView() method.
To let the system decide the best orientation in full-screen mode add this line to onShowCustomView(View view, CustomViewCallback callback) method:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
UPDATE : 09-07-2017
Or you can use a VideoEnabledWebView library for full screen viedo player in webview and much more .
Link : GitHub
I'm new to programming and I'm trying to make an application using Android Studio. So, what I want is something like this
Output I want:
And here's my code:
list_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:paddingBottom="20dp"
android:paddingLeft="20dp"
android:paddingTop="20dp"
android:id="#+id/iconimage"/>
<TextView
android:layout_width="match_parent"
android:layout_height="55dp"
android:padding="16dp"
android:textColor="#000000"
android:textSize="12sp"
android:id="#+id/submenu"
android:gravity="center_vertical" />
</LinearLayout>
list_submenu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textColor="#000000"
android:layout_marginLeft="44dp"
android:textSize="12sp"
android:id="#+id/submenu"/>
</LinearLayout>
MainActivity.java
package com.example.mokui.hopeful;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
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.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
View view_Group;
private DrawerLayout mDrawerLayout;
ExpandableListAdapter mMenuAdapter;
ExpandableListView expandableList;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
// icons
static int[] icon = {R.drawable.home, R.drawable.write};
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
expandableList.setIndicatorBounds(expandableList.getRight()- 80, expandableList.getWidth());
} else {
expandableList.setIndicatorBoundsRelative(expandableList.getRight()- 80, expandableList.getWidth());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
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();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
expandableList = (ExpandableListView) findViewById(R.id.navigationmenu);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
/* ------------------------------EXPAND EXTENSION --------------------------------- */
if (navigationView != null) {
setupDrawerContent(navigationView);
}
prepareListData();
mMenuAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expandableList.setAdapter(mMenuAdapter);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView,
View view,
int groupPosition,
int childPosition, long id) {
//Log.d("DEBUG", "submenu item clicked");
Toast.makeText(MainActivity.this,
"Header: "+String.valueOf(groupPosition) +
"\nItem: "+ String.valueOf(childPosition), Toast.LENGTH_SHORT)
.show();
view.setSelected(true);
if (view_Group != null) {
view_Group.setBackgroundColor(Color.parseColor("#ffffff"));
}
view_Group = view;
view_Group.setBackgroundColor(Color.parseColor("#DDDDDD"));
mDrawerLayout.closeDrawers();
return false;
}
});
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
//Log.d("DEBUG", "heading clicked");
return false;
}
});
/* ------------------------------EXPAND EXTENSION --------------------------------- */
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding data header
listDataHeader.add("Main Map");
listDataHeader.add("Create Post");
listDataHeader.add("Statistics");
listDataHeader.add("");
listDataHeader.add("Edit Account");
listDataHeader.add("Logout");
// listDataHeader.add("menu3");
// Adding child data
List<String> heading1 = new ArrayList<String>();
List<String> heading2 = new ArrayList<String>();
List<String> heading3 = new ArrayList<String>();
heading3.add("HeatMap and Graphs");
List<String> heading4 = new ArrayList<String>();
List<String> heading5 = new ArrayList<String>();
List<String> heading6 = new ArrayList<String>();
listDataChild.put(listDataHeader.get(0), heading1);// Header, Child data
listDataChild.put(listDataHeader.get(1), heading2);
listDataChild.put(listDataHeader.get(2), heading3);
listDataChild.put(listDataHeader.get(3), heading4);
listDataChild.put(listDataHeader.get(4), heading5);
listDataChild.put(listDataHeader.get(5), heading6);
} /* ---------------------------------------- */
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#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.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
} */
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
ExpandableListAdapter.xml
package com.example.mokui.hopeful;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private List<String> mListDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> mListDataChild;
ExpandableListView expandList;
public ExpandableListAdapter(Context context,
List<String> listDataHeader,
HashMap<String,
List<String>> listChildData
// ,ExpandableListView mView
)
{
this.mContext = context;
this.mListDataHeader = listDataHeader;
this.mListDataChild = listChildData;
//this.expandList = mView;
}
#Override
public int getGroupCount() {
int i = mListDataHeader.size();
//Log.d("GROUPCOUNT", String.valueOf(i));
return i;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.mListDataChild.get(
this.mListDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.mListDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
//Log.d("CHILD", mListDataChild.get(this.mListDataHeader.get(groupPosition))
// .get(childPosition).toString());
return this.mListDataChild.get(
this.mListDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_header, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.submenu);
ImageView headerIcon = (ImageView) convertView.findViewById(R.id.iconimage);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
//lblListHeader.setText(headerTitle.getIconName());
// headerIcon.setImageResource(MainActivity.icon[groupPosition]);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_submenu, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.submenu);
txtListChild.setText(childText);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
But so far this is what I got: My current output result:
I just want the Statistics Option to be the only one that collapses. But mine turns out that everything is collapsable.
Hope this will help you...
You can use Linearlayout and provide animation to that linearlayout.
To expand the section, You just have to call this method inside your Statistics Option click listener :
llHidden.measure(MeasureSpec.EXACTLY, MeasureSpec.EXACTLY); // llHidden is the layout which will be GONE as visibility initially, later it will be visible inside Statistics Option.
expand1(llHidden, llHidden.getMeasuredHeight());
To collapse the section, You just have to call this method inside your Statistics Option click listener :
collapse1(llHidden);
/**
* To expand any view with smooth animation
*/
#SuppressLint("NewApi")
public static void expand1(final View v, final int height) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
v.measure(LayoutParams.MATCH_PARENT, height);
final int targtetHeight = height;
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1 ? height
: (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return false;
}
};
a.setDuration((int) (targtetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
} else {
v.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(widthSpec, heightSpec);
ValueAnimator mAnimator = slideAnimator(0, v.getMeasuredHeight(), v);
mAnimator.start();
}
}
/**
* To Collapse any view with smooth animation
*/
#SuppressLint("NewApi")
public static void collapse1(final View v) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
v.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return false;
}
};
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
} else {
int finalHeight = v.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0, v);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
v.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimator.start();
}
}
I am doing an app for making a call directly from an image button inside my app. I want the app to be worked with both API 22 and 22. But while making the minSDK as 22, I am getting an error.
How to make it work??
MainActivity.java
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this.mContext;
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);
}
#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.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
if (mContext.checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 4636));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
}
break;
}
}
}
The error is under checkSelfPermission
I had give the permission in Manifest...
You have to asked the runtime permission while compiling agaisnt 6.0
public static final int REQUEST_READ_PERMISSION =111;
// before on create as global variable
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
f (CheckPermission(this, Manifest.permission.CALL_PHONE)) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 4636));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else {
RequestPermission(YourActivityName.this, Manifest.permission.CALL_PHONE, REQUEST_READ_PERMISSION );
}
break;
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_READ_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 4636));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else {
ShowToast(getString(R.string.permission_needed_sms));
}
return;
}
}
}
How show Banner Ads on Newspaper Link "Webview" Android Eclipse
I already set Admob "Banner Ads and Interstitial Ads" on my Project. Interstitial Ads Work Correctly but Banner Ads not Show on Webview.
Here my Java & xml Code
Details_Newspaper.Java
package com.nasir.newspaper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
#SuppressLint("SetJavaScriptEnabled")
public class Details_Newapaper extends Activity {
WebView mWebview;
AdView mAdView;
private InterstitialAd interAd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Adds Progrss bar Support
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.details_newapaper );
// For Banner Ads View
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// For Interstitial Ads View
interAd = new InterstitialAd(this);
interAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest_FC = new AdRequest.Builder().build();
interAd.loadAd(adRequest_FC);
interAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
displayInterstitial();
}
});
getOverflowMenu();
// Makes Progress bar Visible
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebview.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
final Activity Activity = this;
mWebview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
Activity.setTitle("Loading..... Please Wait");
Activity.setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
Activity.setTitle(R.string.app_name);
}
});
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(Activity, description, Toast.LENGTH_SHORT).show();
}
});
String customHtml = getIntent().getStringExtra("Newspaper_Name");
mWebview.loadUrl(customHtml);
setContentView(mWebview);
mWebview.getSettings().setBuiltInZoomControls(true);
}
// On Back Button Press, Go to Website Back
#Override
public void onBackPressed() {
if (mWebview.isFocused() && mWebview.canGoBack()) {
mWebview.goBack();
} else {
super.onBackPressed();
finish();
}
}
// For Interstitial Ads View
public void displayInterstitial() {
if (interAd.isLoaded()) {
interAd.show();
}
}
/** Called when leaving the activity */
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
/** Called when returning to the activity */
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
/** Called before the activity is destroyed */
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
// inflate for action bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.refresh_main, menu);
return true;
}
// handle click events for action bar items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
showToast("Refresh was clicked.");
return true;
// case R.id.share:
// showToast("Share was clicked.");
// return true;
//
default:
return super.onOptionsItemSelected(item);
}
}
// put the other two menu on the three dots (overflow)
private void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
java.lang.reflect.Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// so that we know something was triggered
public void showToast(String msg){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
details_newspaper.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top|fill_vertical"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-1528948212400372/9325301249" >
</com.google.android.gms.ads.AdView>
</RelativeLayout>