Issue
I try to set the statusBarColor of my Android app by pressing a button in my web application. I got this working but the application will only display a blue status bar when I press the blue button twice. What am I doing wrong?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.loadUrl("https://myurl.com");
}
public void setColor(String color){
if(Build.VERSION.SDK_INT >= 21){
getWindow().setStatusBarColor(Color.parseColor(color));
}
}
}
--
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void setStatusBarColor(String color) {
((MainActivity)mContext).setColor(color);
}
}
--
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="button" value="White" onClick="setStatusBarColor('#ffffff');" />
<input type="button" value="Blue" onClick="setStatusBarColor('#0073cf')" />
<script type="text/javascript">
function setStatusBarColor(color) {
Android.setStatusBarColor(color);
}
</script>
</body>
</html>
--
Any help will be much appreciated. I am out of options here :-(
UPDATE:
Upon debugging a little deeper I get:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Solution
Ok, I got this working... I needed to add "runOnUiThread" around my setStatusBarColor android function. So my setColor function needs to be:
public void setColor(final String color){
runOnUiThread(new Runnable() {
@Override
public void run() {
if(Build.VERSION.SDK_INT >= 21){
getWindow().setStatusBarColor(Color.parseColor(color));
}
}
});
}
Answered By - Peter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.