This question already has answers here:
Display Animated GIF
(29 answers)
Closed 8 years ago.
Hey I'm new to android programming.
I want to know how I can easily implement a GIF in my Android app.
What I have to do?
I tried this, but I do something wrong. It's not working. >>THIS<<
Basically i am giving you following example which loads image online from some web-site and change it each after some time duration.
public class Gif_First extends Activity {
WebView mWebView;
int i = 0;
CountDownTimer mTimer;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.animation);
mTimer = new CountDownTimer(15000, 1000) {
private String[] myArray = {
"http://i.share.pho.to/09d99399_o.gif",
"http://i.share.pho.to/220dd194_o.gif",
"http://i.share.pho.to/6f3a5ae4_o.gif",
"http://i.share.pho.to/1b264cb7_o.gif",
"http://i.share.pho.to/824b1aab_o.gif",
"http://i.share.pho.to/c6728fb8_o.gif",
"http://i.share.pho.to/5508a2e1_o.gif",
"http://i.share.pho.to/aa64f9a9_o.gif",
"http://i.share.pho.to/d4619e93_o.gif",
"http://i.share.pho.to/2d50de0a_o.gif",
"http://i.share.pho.to/23c030eb_o.gif",
"http://i.share.pho.to/d6e3ccad_o.gif",
"http://i.share.pho.to/eaaeaf88_o.gif",
"http://i.share.pho.to/9708dd88_o.gif",
"http://i.share.pho.to/7f879974_o.gif",
"http://i.share.pho.to/efe8afa3_o.gif",
"http://i.share.pho.to/259954ac_o.gif",
"http://i.share.pho.to/bdbc28f2_o.gif" };
int currentIndex = 0;
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if (currentIndex < myArray.length) {
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
} else {
currentIndex = 0;
if (currentIndex < myArray.length)
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
mTimer.start();
}
mTimer.start();
}
// code comment end
};
mTimer.start();
mWebView = (WebView) findViewById(R.id.webviewActionView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://i.share.pho.to/49cf97de_o.gif");
mWebView.setWebViewClient(new WebSliderWebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(mWebView, url);
//Toast.makeText(getApplicationContext(), "Done!",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
//Toast.makeText(getApplicationContext(),
// "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class WebSliderWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
and here is XML File.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DogView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<WebView
android:id="#+id/webviewActionView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I think all link is dead but you can upload some image over there and change the link and then try.
Related
I am using Youtube API for android. Below is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = true;
}
});
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
Toast.makeText(this,"Back pressed",Toast.LENGTH_LONG).show();
if(isFullScreen)
{
player.setFullscreen(false);
}
else
{
super.onBackPressed();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--<com.google.android.youtube.player.YouTubePlayerView-->
<!--android:id="#+id/youtube_view"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"/>-->
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
When the Full Screen is visible and if the user clicked back, I want my Activity to be displayed. Instead what is happening now is the back button exists from the app.
How can I fix this?
UPDATE
I Identified the error, inside the setOnFullScreenListener it was never identified the app is in Full screen, even though it is. I tried forcing the boolean into true, but it ended up crashing saying the player is null
I'm not sure but in your onFullScreen() override method, you have set
isFullScreen = true;
Rather, use
isFullScreen = b;
Hope this helps.
I found the answer, just remove the if condition in onInitializationSuccess. Below is the code.
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
this.player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = b;
}
});
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
if(isFullScreen)
{
Toast.makeText(this,"Full Screen",Toast.LENGTH_LONG).show();
player.setFullscreen(false);
}
else
{
Toast.makeText(this,"Not Full Screen",Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
}
hello there i have created an app for playing Youtube videos i works fine but i want when i click on next button the next videos plays. how i will create an array for it which contain the youtube videos link. i m new to Android programming plz help.
public class TutorialsActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String DEVELOPER_KEY = "AIzaSyAIeerJ_5ClQHLtIpXtk5DH2S4mZ9lwGKs";
private static final String VIDEO_ID = "eQW4R5gLlUk";
private static final String VIDEO_ID1 = "H2c_x4YWx7I";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerFragment myYouTubePlayerFragment;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorials);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager().findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
btnNext = (Button) findViewById(R.id.btnNext);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.cueVideo(VIDEO_ID1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}
just i shared my working source of your requirement.
SampleActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import java.util.ArrayList;
import www.ns7.tv.R;
import www.ns7.tv.controller.YoutubeManager;
public class SampleActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, View.OnClickListener {
private static final String TAG = "YoutubeLiveTvActivity";
private Button mBtnNext;
private YouTubePlayerView mYouTubePlayerView = null;
private YouTubePlayer mLiveTvPlayer = null;
private ArrayList<String> mVideoIdList = new ArrayList<>();
private int mOffset = 0;
private String mCurrentVideoId;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.sample);
mBtnNext = (Button) findViewById(R.id.btnNext);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
mBtnNext.setOnClickListener(this);
updateVideoIdList();//add all video id in list
updateVideoId();//set current video id to mCurrentVideoId string
}
private void updateVideoId() {
if (mOffset >= mVideoIdList.size())
mOffset = 0;
mCurrentVideoId = mVideoIdList.get(mOffset);
}
private void updateVideoIdList() {
mVideoIdList.clear();
mVideoIdList.add("p0JcLbXfYXA");
mVideoIdList.add("63pKwVE4Uog");
mVideoIdList.add("QJXsurYoJ10");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
try {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mLiveTvPlayer = youTubePlayer;
// mLiveTvPlayer.setOnFullscreenListener(YoutubeLiveTvActivity.this);
if (!b) {
mYouTubePlayerView.setVisibility(View.VISIBLE);
youTubePlayer.loadVideo(mCurrentVideoId);
}
} catch (Exception e) {
Log.e(TAG, " error : ", e);
}
}
#Override
protected void onResume() {
super.onResume();
if (mLiveTvPlayer == null) {
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
} else {
mLiveTvPlayer.loadVideo(mCurrentVideoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onDestroy() {
if (mLiveTvPlayer != null) {
mLiveTvPlayer.release();
}
if (mYouTubePlayerView != null) {
mYouTubePlayerView.removeAllViews();
}
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnNext:
{
mOffset++;// move the mOffset to next video id
updateVideoId();
mLiveTvPlayer.loadVideo(mCurrentVideoId);//load next video
}
break;
}
}
}
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/btnNext"
android:background="#android:color/black"
>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
/>
</RelativeLayout>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Next"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Above code youtube video play at 0 position when you click next button , next video will be play. if list last item reached then it will again move to 0 position.
Output :
I'm using the following code for a slide in / slide out toggle for an AppBarLayout.
public void showToolbar(boolean show) {
if (appBar == null) {
Log.e(TAG, "showToolbar: Toolbar is null");
return;
}
boolean toolbarShown = Utils.isViewVisible(appBar);
Log.d(TAG, "showToolbar: shown:" +shown);
boolean changed = (show != toolbarShown);
if (changed) {
if (show) {
Log.d(TAG, "showToolbar: showing");
appBar.setVisibility(View.VISIBLE);
appBar.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
appBar.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationEnd(Animator animator) { }
#Override
public void onAnimationCancel(Animator animator) { }
#Override
public void onAnimationRepeat(Animator animator) { }
})
.start();
} else {
Log.d(TAG, "showToolbar: hiding");
appBar.animate()
.translationY(-toolbar.getBottom())
.setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) { }
#Override
public void onAnimationEnd(Animator animator) {
appBar.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationCancel(Animator animator) { }
#Override
public void onAnimationRepeat(Animator animator) { }
})
.start();
}
} else {
Log.d(TAG, "showToolbar: no change");
}
}
The animation works perfectly except for the first time showToolbar(true) is called to show the toolbar. The view just shows up without animation the first time. I have scoured the site and found similar questions but the solutions doesn't seem to be working for me.
It might be worth noting that this happens only when we want the appBar to be hidden first. My guess is that maybe for the animation to
Update 1:
public static boolean isViewVisible(View view) {
if (View.VISIBLE == view.getVisibility()) return true;
else return false;
}
Update 2
I have removed isViewWithinScreenBounds() method because that check isn't really needed.
Be sure to set the initial values for visibility and translationY.
If you want your toolbar to be initially hidden and show up with the first animation, be sure to set android:visibility="invisible" and NOT "gone", and negative android:translationY like -56dp.
Try with this
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:translationY="-120dp"
android:layout_height="120dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SOME TEXT HERE" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Activity code
#BindView(R.id.app_bar)
AppBarLayout appBar;
#BindView(R.id.toolbar)
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
animateToolbar(false); //Just for testing purpose - delay execute of function animateToolbar() for 4 seconds
}
}, 4000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
animateToolbar(true);
return super.onCreateOptionsMenu(menu);
}
private void animateToolbar(boolean show) {
if (show) {
// As you can see in the xml layout initial position of the appBar is translated by its height to the top of the screen "-" sign
// Slide int from out of the screen to initial position -> from -120 dp (height of the app bar, see xml) to 0 dp
appBar.animate()
.translationY(0)
.setDuration(1000)
.start();
} else {
// Slide out from initial position to the top of the screen -> from 0 dp to -120 dp (height of the app bar, see xml)
appBar.animate()
.translationY(-appBar.getHeight())
.setDuration(1000)
.start();
}
}
This is my splashscreen activity.
public class Splash extends Activity {
private static int SPLASH_TIME_OUT=10000;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Timer r=new Timer();
new Handler().postDelayed(r,SPLASH_TIME_OUT);
}
class Timer implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
}
This is my MainActivity. This activity Should be performed in background while splashscreen is on the front. Is it advisable to use AsyncTask. How to do that?
If not AsyncActivity, What can I use?
public class MainActivity extends Activity {
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.output);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAppCacheEnabled(false);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
);
webview.loadUrl("http://www.example.com");
}
//this is to go back to previous pages if exists
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);
}
}
If possible can I set the time for the splashscreen to view as long as the url is loaded without giving time?
The second attempt
public class MainActivity extends Activity {
WebView webview;
private boolean isSplashOn = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
webview = (WebView)findViewById(R.id.output);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAppCacheEnabled(false);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
public void onPageFinished(WebView view, String url) {
if(isSplashOn) {
webview.setBackgroundDrawable(null);
webview.setBackgroundColor(0);
isSplashOn = false;
}
super.onPageFinished(view, url);
}
}
);
webview.loadUrl("http://www.example.com");
}
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);
}
}
Guys. Still the problem is't solved. Need some help
You can use the simple trick -
I was showing a loading spinner till the page was being loaded in background.
Thus I had used two web views.
In your case, you can use ImageView or any other view.
XML file will like this -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
//Actual webview
<WebView
android:id="#+id/actual_webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
//Any view you want to show while webpage is loading
<WebView
android:id="#+id/spinner_webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
...
</RelativeLayout>
Now, in your JAVA file-
//initially, make actual_webview invisible
actual_webview.setVisibility(View.INVISIBLE);
Also, in
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// make spinner_webview invisible
spinner_webview.setVisibility(View.INVISIBLE);
// make actual_webview visible
actual_webview.setVisibility(View.VISIBLE);
}
Also,
shouldOverrideUrlLoading(...)
onPageStarted(...)
onPageFinished(...)
In all these methods, you get the URL and can check which URL is being loaded or finished loading.
According to the URL you can decide whether to show / hide the splash screen.
You can do it without AsyncTask and you can hide the splash screen when the page loaded without a timer.
WebViewClient class has a method onPageFinished() which will be called once the page has been loaded. You can make use of it.
In you project folder, place your splash screen images with name 'splash_screen.png' (or whatever name you want. If you want to use a different name then change this line webView.setBackgroundResource(R.drawable.splash_screen); to map to your splash screen image file) under res/drawable-xxx with corresponding resolutions.
For Eg:
I followed these resolutions for my app's splash screen.
hdpi - 400x800
ldpi - 240x320
mdpi - 320x480
xdpi - 640x960
And try this code:
public class MainActivity extends Activity {
final Activity activity = this;
private WebView webView;
private boolean isSplashOn = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setBackgroundColor(0);
webView.setBackgroundResource(R.drawable.splash_screen);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.setWebViewClient(new MyWebClient());
webView.loadUrl("http://www.google.com");
}
public class MyWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if(!isSplashOn) {
webView.setBackgroundDrawable(null);
webView.setBackgroundColor(0);
isSplashOn = true;
}
super.onPageFinished(view, url);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
if(webView.canGoBack()) {
webView.goBack();
return true;
}else {
activity.finish();
}
}
return super.onKeyDown(keyCode, event);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
</LinearLayout>
EDIT:
By the way i found the issue with your code. You are trying to set the splash screen to the webview before instantiating it.
Change your code from this:
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
webview = (WebView)findViewById(R.id.output);
to this:
webview = (WebView)findViewById(R.id.output);
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
Why does the splash has to be an activity?
You can make it a full screen ImageView in the bottom of your layout and hide it using a handler:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isDestroyed())
return;
mSplashView.setVisibility(View.GONE);
}
},2000);
First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"