When I declare and try to get a reference to my button, which I declare in XML, the app won't open and I don't know why. PLEASE try to explain to me why not -- don't just give a link.
Here's the code:
public class MainActivity extends AppCompatActivity {
final String stream="<iframe width=\"300\" height=\"193\" src=\"http://cdn.livestream.com/embed/sl48?layout=4&color=0xffad4b&autoPlay=true&mute=false&iconColorOver=0xe17b00&iconColor=0xb96500&allowchat=true&height=193&width=300\" style=\"border:0;outline:0\" frameborder=\"0\" scrolling=\"no\"></iframe>";
// Button button = (Button) findViewById(R.id.home);
//final Button button1 = (Button) findViewById(R.id.stream);
//final Button button2 = (Button) findViewById(R.id.contatti);
WebView custumWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
custumWebView = (WebView) findViewById(R.id.webView);
custumWebView.loadData(stream, "text/html", null);
custumWebView.getSettings().setJavaScriptEnabled(true);
custumWebView.getSettings().setLoadsImagesAutomatically(true);
custumWebView.clearHistory();
custumWebView.clearCache(true);
custumWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
}
public class CustomWebView extends WebView {
public CustomWebView (Context context) {
super( context );
init();
}
public CustomWebView (Context context, AttributeSet attrs) {
super( context, attrs );
init();
}
public CustomWebView (Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
init();
}
public CustomWebView (Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
super( context, attrs, defStyle, privateBrowsing );
init();
}
protected void init () {
getSettings().setJavaScriptEnabled( true );
setWebViewClient( new CustomWebViewClient() );
setDownloadListener( new CustomDownloadListener() );
}
protected boolean overrideUrlLoading (WebView view, String url) {
// ANY CUSTOM LOGIC GOES HERE
view.loadUrl(url);
return true;
}
protected void pageFinished (WebView view, String url) {
}
protected void downloadStarted(String url, String mimetype) {
try {
//Start new activity to load the specific url
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), mimetype);
getContext().startActivity(intent);
//custumWebView.loadData(stream, "text/html", null);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Default webview client.
*/
protected class CustomWebViewClient extends WebViewClient {
/**
* Constructor, default.
*/
public CustomWebViewClient () {
}
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
return overrideUrlLoading( view, url );
}
#Override
public void onPageFinished (WebView view, String url) {
pageFinished(view, url);
}
}
protected class CustomDownloadListener implements DownloadListener {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
downloadStarted(url, mimetype);
}
}
}
and here the 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_below="#+id/stream"
android:layout_alignRight="#+id/stream"
android:layout_alignEnd="#+id/stream"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:id="#+id/home"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stream"
android:id="#+id/stream"
android:layout_alignTop="#+id/home"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contatti"
android:id="#+id/contatti"
android:layout_above="#+id/webView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:minHeight="50dp"
android:minWidth="400dp" />
</RelativeLayout>
The CustomWebView class is so I don't get errors with loadData for the streaming site. I don't know why this class is working but it is. I copied it from the livestream support site, I'm only a newbie and I'm trying to learn.
If you're referring to these two lines of code at the top of your class:
// Button button = (Button) findViewById(R.id.home);
//final Button //final Button button2 = (Button) findViewById(R.id.contatti);
That will not work in that location. Those buttons are created in your XML layout. You cannot get a reference to a button declared in an XML layout before you first call setContentView() in your onCreate() method. You must do this.
This is what you need to do:
public class MainActivity extends AppCompatActivity {
private Button mButton;
private Button mButton1;
private Button mButton2;
// declare any other fields you require
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.home);
mButton1 = (Button) findViewById(R.id.stream);
mButton2 = (Button) findViewById(R.id.contatti);
// Your other initialization code
}
Please note that you cannot declare those Buttons as final fields, as they are not instantiated in a constructor (onCreate() is not a constructor).
Related
I'm trying to use custom WebChromeClient, but for some URL's in android marshmallow and nougat it show's me below error in logcat and don't load URL, but it's working fine for pre marshmallow.
The error:
W/cr_AwContentsClient: Denied starting an intent without a user
gesture
What is the meaning the error? How should I handle it?
The webview:
#SuppressLint("SetJavaScriptEnabled")
public class MyWebView extends BaseWebView {
public BrowserWebView(Context context, AttributeSet attrs) {
super(context, attrs);
getSettings().setJavaScriptEnabled(true);
setWebChromeClient(new WebChromeClient());
}
}
The activity :
public class MyActivity extends Activity {
private MyWebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_browser);
webView = (MyWebView) findViewById(R.id.my_web_view);
webView.loadUrl("https://.../");
}
#Override
public void onBackPressed() {
// Check if the key event was the Back button and if there's history
if (webView != null && webView.canGoBack()) {
webView.goBack();
return;
}
super.onBackPressed();
}
}
Activity layout XML:
<?xml version="1.0" encoding="utf-8"?>
<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=".view.activity.MyActivity">
<com.test.MyWebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/my_web_view"/>
</RelativeLayout>
I have can WebView in Fragment, when move tab Fragment,and I touch Button aboutUs--> move in Fragment AboutUs; I repeat about 10times.
Error is same picture.
can everyone help me?. Thank :
Code Fragment load WebView :
public class InAppBrowserFragment
extends BaseFragment {
private static final String LINK_PAGE = "linkPage";
private static final String TITLE_ACTION_BAR = "titleActionBar";
#InjectView(R.id.web_settings)
WebView mWebViewSettings;
#InjectView(R.id.actionbar_settings_sub)
ActionBar mActionBar;
#InjectView(R.id.img__settings_background)
ImageView mImgSettingsBackground;
/**
* Static method used to create an instance for this fragment.
*
* #return New instance of Fragment.
*/
public static InAppBrowserFragment newInstance(String titleActionBar,
String linkPage) {
final InAppBrowserFragment fragment = new InAppBrowserFragment();
final Bundle data = new Bundle();
if (titleActionBar != null) {
data.putString(LINK_PAGE,
linkPage);
data.putString(TITLE_ACTION_BAR,
titleActionBar);
}
// Attach data with fragment.
fragment.setArguments(data);
return fragment;
}
#Override
protected int getLayoutResourceId() {
return R.layout.fragment_in_app_browser;
}
#Override
protected void initUi(final Bundle savedInstanceState) {
String titleActionBar = getArguments().getString(TITLE_ACTION_BAR);
//set background
CommonUtil.displayImage(getActivity(),
CommonUtil.getDrawableResource(R.drawable.img_random_frontpage_1),
this.mImgSettingsBackground,
0,
0,
0,
true,
false,
null);
//set UI Action Bar
this.mActionBar.setupUI(null,
titleActionBar,
R.drawable.ab_ic_back,
0,
"");
this.mActionBar.setButtonRightPadding(0);
this.mActionBar.setButtonLeftListener(new ActionBar.IActionBarButtonLeftListener() {
#Override
public void onButtonLeftClicked(final View view) {
popBack(true);
mWebViewSettings.canGoBack();
}
});
}
#Override
protected void loadData(final Bundle savedInstanceState) {
String linkPage = getArguments().getString(LINK_PAGE);
// Init webview setting
WebSettings settings = mWebViewSettings.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(true);
settings.setSupportZoom(true);
mWebViewSettings.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
});
mWebViewSettings.loadUrl(linkPage);
}
}
Conrect:
Inconrect:
i fix sucess :(set wrap_content for Webview )
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/CreateTrips.Widget.ScreenContent.Fragment">
<ImageView
android:id="#+id/img__settings_background"
style="#style/CreateTrips.Widget.BackgroundImage"
android:contentDescription="#null"/>
<com.createtrips.ui.widgets.ActionBar
android:id="#+id/actionbar_settings_sub"
style="#style/CreateTrips.Widget.ActionBar"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:layout_marginTop="#dimen/widget_action_bar_height"
>
<WebView
android:id="#+id/web_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</FrameLayout>
I'm struggling to find any tutorial to help me put a SurfaceView in a box. A pointer in the right direction would be amazing - not looking for a hand hold through it.
I'd like to be able to apportion an area at the top of the screen for example to do buttons etc and then have a surfaceview filling the rest. However, when I try to modify the code I've used for full screen surfaceView to reference my xml, it all goes a bit wrong.
My code for my main activity is as follows (I've stripped out a lot of the bits I think aren't relevant).
package com.example.mylistviewidea;
import android.os.Bundle;
etc...
public class MainActivity extends Activity implements OnTouchListener {
MyListView myListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myListView = (MyListView) findViewById(R.id.surfaceView1);
}
class MyListView extends SurfaceView implements Runnable {
SurfaceHolder myHolder;
Thread myThread = null;
boolean isRunning = false;
// My Variables
long dT;
int myRed;
public MyListView(Context context) {
super(context);
myHolder = getHolder();
}
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!myHolder.getSurface().isValid())
continue;
Canvas canvas = myHolder.lockCanvas();
canvas.drawARGB(128, 0, 0, 0);
dT = SystemClock.uptimeMillis();
myRed = (int) ((int) 128*(1+Math.sin((double) dT/1000)));
}
}
}
}
My XML is:
<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" >
<SurfaceView
android:id="#+id/surfaceView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/add_entries" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:text="#string/remove_entries" />
</RelativeLayout>
The error I'm getting is:
02-08 11:44:17.885: E/AndroidRuntime(10523): java.lang.RuntimeException: Unable
to start activity ComponentInfo{com.example.mylistviewidea/com.example.mylistviewidea.MainActivity}:
java.lang.ClassCastException: android.view.SurfaceView cannot be cast to
com.example.mylistviewidea.MyListView
Thanks in advance for your help!
Cheers,
Mike
You should have a custom view and use it in your xml.
First create this view
class MyListView extends SurfaceView implements Runnable {
SurfaceHolder myHolder;
Thread myThread = null;
boolean isRunning = true;
// My Variables
long dT;
int myRed;
public MyListView(Context context) {
super(context);
init();
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
myHolder = getHolder();
myHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!myHolder.getSurface().isValid())
continue;
Canvas canvas = myHolder.lockCanvas();
canvas.drawARGB(128, 128, 0, 0);
dT = SystemClock.uptimeMillis();
myRed = (int) ((int) 128 * (1 + Math.sin((double) dT / 1000)));
myHolder.unlockCanvasAndPost(canvas);
}
}
}
Change your xml to 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=".MainActivity" >
<com.example.testant.MyListView
android:id="#+id/surfaceView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="add_entries" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:text="remove_entries" />
and change main activity
public class MainActivity extends Activity {
MyListView myListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myListView = (MyListView) findViewById(R.id.surfaceView1);
new Thread(myListView).start();
}
}
Note that you also have a bug with lock canvas, but this should work fine.
It might be a bit trivial. But try to clean project and then do a rebuild.
OR
Declare a MyListView in a separate java class file and the reference it in your xml layout file,
I made a simple extension of CheckBoxPreference so that I could have my own custom view with an image icon to the left of the title. The code is below:
public class CustomCheckBoxPreference extends CheckBoxPreference {
private Drawable icon;
public CustomCheckBoxPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.CustomCheckBoxPreference, 0, 0);
icon = arr.getDrawable(R.styleable.CustomCheckBoxPreference_icon);
setLayoutResource(R.layout.custom_checkbox_pref);
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
ImageView prefsIcon = (ImageView) view.findViewById(R.id.prefs_icon);
prefsIcon.setImageDrawable(icon);
}
The problem is that for some reason the OnPreferenceChangeListener I set to any CustomCheckboxPreference has no effect and is not stored. I tried overriding some of the android methods for the implementation calling super and then printing a line to see what gets called. Notably callChangeListener does not get called. It is this method that leads to the callback for onPreferenceChanged. I tried throwing in a call to onPreferenceChanged inside of setChecked just to see what would happen and the OnPreferenceChangeListener is null:
getOnPreferenceChangeListener().onPreferenceChange(this, checked);
This is how I set the preferencechangelistener:
mTwitterPref.setChecked(!mTwitter.needsAuth());
mTwitterPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
System.out.println("Twitter Preference Changed!");
if ((Boolean) newValue) {
if (mTwitter.needsAuth()) {
System.out.println("We Need To Login To Twitter!");
IntentUtils.startActivityForResult(ProfileAccountsActivity.this,
TwLoginActivity.class, ACTIVITY_OAUTH);
}
} else {
showDialog(DIALOG_LOGOUT_TWITTER);
}
return false;
}
});
I am a bit confused as to why the preferencechangelistener is not working properly as I only overwrite onBindView and the constructor; I call super in both. Any thoughts?
Set android:focusable="false" and android:clickable="false" on the CheckBox:
<CheckBox
android:id="#+android:id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false" />
More info on this thread: Clickable rows on custom ArrayAdapter
I had the same issue with custom button. I tried the solution provided by #jeanh and it works. But my button was not pressed, only area around it was highlighted. Moreover, what if you have a few buttons? Obviously, that this solution won't work. So, I decided to dig deeper and my solution was below:
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/widget_frame" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:paddingRight="10dp"
android:paddingBottom="5dp"
>
<!-- define my button -->
<Button android:id="#android:id/title"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17sp"
android:typeface="sans"
android:textStyle="bold"
android:textColor="#000000"
></Button>
</RelativeLayout>
Java class:
public class ButtonPreference extends Preference {
private final String TAG = getClass().getName();
public interface ButtonListener {
public void onCustomClick();
}
public ButtonListener buttonListener;
public void setButtonListener(ButtonListener buttonListener){
this.buttonListener = buttonListener;
}
public ButtonPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ButtonPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected View onCreateView(ViewGroup parent){
RelativeLayout layout = null;
try {
LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (RelativeLayout)mInflater.inflate(R.layout.button_preference, parent, false);
//FIND OUR BUTTON IN LAYOUT
Button button = (Button) layout.findViewById(android.R.id.title);
if(button!=null){
Log.e(TAG, "button found");
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(buttonListener!=null){
buttonListener.onCustomClick(); //INVOKE OUR EVENT!
}
}
});
}
}
catch(Exception e)
{
Log.e(TAG, "Error creating info preference", e);
}
return layout;
}
}
HOW TO USE IT? Simple!
public class WallpaperSettings extends PreferenceActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
ButtonPreference defaultSettingsButton = (ButtonPreference) findPreference(EngineCore.pref+"defaultSettings");
defaultSettingsButton.setButtonListener(new ButtonListener() {
#Override
public void onCustomClick() {
Gdx.app.log("ButtonListener", "onCustomClick");
}
});
}
}
I hope it helps someone else.
I found solution !
In my case, I extends DialogPreference to my custom Dialog class,
public class SvDialogPreference extends DialogPreference
I also confuse, because in PreferenceFragment, onPreferenceChange never worked.
SvDialogPreference pref= (SvDialogPreference) findPreference("mainKey");
if( pref != null ) {
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Never execute !
}}
To resolve this. I called "super.callChangeListener" in onDialogClosed.
public class SvDialogPreference extends DialogPreference{
....
#Override
protected void onDialogClosed(boolean positiveResult) {
double InputValue = Double.parseDouble(KEY.getText().toString());
super.callChangeListener(InputValue);
super.onDialogClosed(positiveResult);
}
Now, onPreferenceChange worked fine !
I'm trying to do basic authentication to view a protected url. I want to access the protected url which looks like this:
http://api.test.com/userinfo/vid?=1234
So I do the following with a WebView:
mWebView.setHttpAuthUsernamePassword("api.test.com", "", "me#test.com", "mypassword");
mWebView.loadUrl("http://api.test.com/userinfo/user?uid=53461");
but the authentication doesn't seem to work, I'm just getting an output error page. Am I using the WebView method correctly here?
Update:
Trying with curl:
curl -u me#test.com:mypassword http://api.test.com/userinfo/user?uid=53461
and it pulls the page fine. I tried every combination of the host parameter, the owners of the api don't know what I mean by 'realm' though (and neither do I) - what info could I give them to help this along?
Thanks
Another option is to use a WebViewClient;
webview.setWebViewClient(new MyWebViewClient ());
private class MyWebViewClient extends WebViewClient {
#Override
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.proceed("me#test.com", "mypassword");
}
}
webview.setWebViewClient(new WebViewClient () {
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.proceed("login", "pass");
}
});
The default behavior of a WebView is to discard all authentication requests. Even if setHttpAuthUsernamePassword.
You have to set a WebViewClient and Override the method onReceivedHttpAuthRequest
If you do not mind writing your username and password into the url, then it is not necessary to change your webview client.
Just open the following url in the webview:
http://username:password#api.test.com/userinfo/vid?=1234
In this example realm is By Invitation Only
AuthType Basic
AuthName "By Invitation Only"
AuthUserFile /usr/local/apache/passwd/passwords
Require user rbowen sungo
You may need something other than "" for the second parameter. Contact the developer of the Web site and find out what an appropriate realm should be. Or, use tools like curl to find out what the realm should be.
I never did get setHttpAuthUsernamePassword to work with phonegap's FileTransfer.download (since it doesn't use the webview), but I DID get this to work with phonegap. It's worth noting if any other phonegap people end up on this thread.
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass.toCharArray());
}
});
This is so silly. I hacked something together that worked for me, I hope it'll work for you too.
public class AuthRequestDialogFragment extends DialogFragment
{
#InjectView(R.id.dauth_userinput)
public EditText userinput;
#InjectView(R.id.dauth_passinput)
public EditText passinput;
#OnClick(R.id.dauth_login)
public void login(View view) {
((Callback) getTargetFragment()).login(userinput.getText().toString(), passinput.getText().toString());
this.dismiss();
}
#OnClick(R.id.dauth_cancel)
public void cancel(View view) {
((Callback) getTargetFragment()).cancel();
this.dismiss();
}
public static interface Callback
{
public void login(String username, String password);
public void cancel();
}
#Override
public void onStart() {
super.onStart();
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
getDialog().getWindow().setLayout(width*2/3, height/5*2);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.dialog_authrequest, container);
ButterKnife.inject(this, view);
getDialog().setTitle("Authorization required");
return view;
}
}
And
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dauth_requsertext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The server requires a username and password."
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"/>
<RelativeLayout
android:id="#+id/dauth_centercontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/dauth_usertext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:id="#+id/dauth_passtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Password"
android:layout_below="#+id/dauth_usertext"
android:layout_alignLeft="#+id/dauth_usertext"
android:layout_alignStart="#+id/dauth_usertext"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dauth_userinput"
android:ems="12"
android:layout_alignBottom="#+id/dauth_usertext"
android:layout_toRightOf="#id/dauth_usertext"
android:layout_toEndOf="#id/dauth_usertext"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dauth_passinput"
android:layout_marginTop="20dp"
android:inputType="textPassword"
android:ems="12"
android:layout_alignBottom="#+id/dauth_passtext"
android:layout_toRightOf="#id/dauth_passtext"
android:layout_toEndOf="#id/dauth_passtext"
android:layout_alignLeft="#id/dauth_userinput"
android:layout_alignStart="#id/dauth_userinput"/>
</RelativeLayout>
<Button
android:id="#+id/dauth_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"/>
<Button
android:id="#+id/dauth_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:layout_alignTop="#+id/dauth_cancel"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_toLeftOf="#+id/dauth_cancel"/>
</RelativeLayout>
And
public class WebViewFragment extends Fragment implements AuthRequestDialogFragment.Callback {
#Override
public void login(String username, String password) {
Log.d(this.getClass().getName(), "Login");
myWebViewClient.login(username, password);
}
#Override
public void cancel() {
Log.d(this.getClass().getName(), "Cancel");
myWebViewClient.cancel();
}
And the most important:
private class MyWebViewClient extends WebViewClient {
private WebView myView;
private HttpAuthHandler httpAuthHandler;
private String host;
private String realm;
#Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
AuthRequestDialogFragment authRequestDialogFragment = new AuthRequestDialogFragment();
FragmentManager fragmentManager = ((getActivity()).getSupportFragmentManager());
authRequestDialogFragment.setTargetFragment(WebViewFragment.this, 0);
authRequestDialogFragment.show(fragmentManager, "dialog");
this.httpAuthHandler = handler;
this.myView = view;
this.host = host;
this.realm = realm;
}
public void login(String username, String password) {
httpAuthHandler.proceed(username, password);
myView = null;
httpAuthHandler = null;
host = null;
realm = null;
}
public void cancel() {
super.onReceivedHttpAuthRequest(myView, httpAuthHandler, host, realm);
myView = null;
httpAuthHandler = null;
host = null;
realm = null;
}
}
Uses dependency:
compile 'com.jakewharton:butterknife:6.0.0'