WebView in a Dialog (loading assets) and not laid out - android

I'm on Android 2.2 and I'm creating a dialog with a WebView inside it:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = new Dialog(this);
//.....
dialog.setContentView(R.layout.dialoghelp);
WebView v = (WebView)dialog.findViewById(R.id.helpWebView);
v.loadUrl("file:///android_asset/help.html");
//......
return dialog;
}
It's working, but the first time I open the dialog the WebView isn't laid out, even if the content is actually loaded.
I know this because with HierarchyViewer I can see the contents and forcing a layout request I get to see them in the emulator too. Also, if I just cancel the dialog and reopen it, everything works.
Who's wrong, Android or me? I tried putting the loading in onPrepareDialog() but it's the same.
EDIT
I changed WebView's layout params from fill_parent to wrap_content and this way it works. I can see it opening with a 0 height, then after the loading it grows up. The width worked even before.

Well I think you may need to override the Dialog class , something like what facebook sdk has implemented :-
here is there code
public class FbDialog extends Dialog {
static final int FB_BLUE = 0xFF6D84B4;
static final float[] DIMENSIONS_DIFF_LANDSCAPE = {20, 60};
static final float[] DIMENSIONS_DIFF_PORTRAIT = {40, 60};
static final FrameLayout.LayoutParams FILL =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
static final String DISPLAY_STRING = "touch";
static final String FB_ICON = "icon.png";
private String mUrl;
private DialogListener mListener;
private ProgressDialog mSpinner;
private ImageView mCrossImage;
private WebView mWebView;
private FrameLayout mContent;
public FbDialog(Context context, String url, DialogListener listener) {
super(context, android.R.style.Theme_Translucent_NoTitleBar);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
requestWindowFeature(Window.FEATURE_NO_TITLE);
mContent = new FrameLayout(getContext());
/* Create the 'x' image, but don't add to the mContent layout yet
* at this point, we only need to know its drawable width and height
* to place the webview
*/
createCrossImage();
/* Now we know 'x' drawable width and height,
* layout the webivew and add it the mContent layout
*/
int crossWidth = mCrossImage.getDrawable().getIntrinsicWidth();
setUpWebView(crossWidth / 2);
/* Finally add the 'x' image to the mContent layout and
* add mContent to the Dialog view
*/
mContent.addView(mCrossImage, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addContentView(mContent, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
private void createCrossImage() {
mCrossImage = new ImageView(getContext());
// Dismiss the dialog when user click on the 'x'
mCrossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onCancel();
FbDialog.this.dismiss();
}
});
Drawable crossDrawable = getContext().getResources().getDrawable(R.drawable.close);
mCrossImage.setImageDrawable(crossDrawable);
/* 'x' should not be visible while webview is loading
* make it visible only after webview has fully loaded
*/
mCrossImage.setVisibility(View.INVISIBLE);
}
private void setUpWebView(int margin) {
LinearLayout webViewContainer = new LinearLayout(getContext());
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new FbDialog.FbWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mWebView.setVisibility(View.INVISIBLE);
mWebView.getSettings().setSavePassword(false);
webViewContainer.setPadding(margin, margin, margin, margin);
webViewContainer.addView(mWebView);
mContent.addView(webViewContainer);
}
private class FbWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Util.logd("Facebook-WebView", "Redirect URL: " + url);
if (url.startsWith(Facebook.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
if (error == null) {
mListener.onComplete(values);
} else if (error.equals("access_denied") ||
error.equals("OAuthAccessDeniedException")) {
mListener.onCancel();
} else {
mListener.onFacebookError(new FacebookError(error));
}
FbDialog.this.dismiss();
return true;
} else if (url.startsWith(Facebook.CANCEL_URI)) {
mListener.onCancel();
FbDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_STRING)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(
new DialogError(description, errorCode, failingUrl));
FbDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Util.logd("Facebook-WebView", "Webview loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mSpinner.dismiss();
/*
* Once webview is fully loaded, set the mContent background to be transparent
* and make visible the 'x' image.
*/
mContent.setBackgroundColor(Color.TRANSPARENT);
mWebView.setVisibility(View.VISIBLE);
mCrossImage.setVisibility(View.VISIBLE);
}
}
}

Related

How to create a popup when button is pushed in Android?

How can I create a custom popup class that accepts a simple string message? Im new to Android and help with code will be appreciated.
When a button is pushed in the main layout, the popup must pop up on the screen.
Custom popup class
public class CustomPopup extends PopupWindow {
private String message;
private Double anchorX;
private Double anchorY;
PopupWindow popup;
public CustomPopup(String message) {
super();
this.message = message;
}
public void showPopup(Activity context) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
Main Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText messageTxt = (EditText) findViewById(R.id.messageTxt);
Button generateBtn = (Button) findViewById(R.id.generateBtn);
String message = messageTxt.getText().toString();
final CustomPopup popup = new CustomPopup(message);
generateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.showPopup();
}
});
}
}
You can change the following code any way you need. This is just an example of how you make and implement a custom DialogFragment.
He is the code I use. I find it quite flexible because you can create several similar dialogs for slightly different tasks. You will need to create a layout file - this gives you a great deal of flexibility on function and style.
My layout file is fragment_ok_cancel_dialog.
To satisfy your requirements just create your own layout file with all the elements in it you need (like your image).
In the Activity that calls the dialog you will need to implement the Listener.
implements OkCancelDialogFragment.OkCancelDialogListener
Another advantage is with my code you can change the title and the message to fit the needs of any Activity.
private void callMyDialog(){
//Customize the title and message as needed
String title = "This is my dialog title";
String mess = "This is my dialog message";
OkCancelDialogFragment dialog = OkCancelDialogFragment.newInstance(title, mess);
dialog.show(getFragmentManager(), "OkCancelDialogFragment2");
}
Now you need to implement the dialog callback in the Activity that calls the DialogFragment.
#Override
public void onFinishOkCancelDialog(boolean submit) {
if(submit){
// Do something positive
}
else{
// Do something negative
}
}
Now the code for the DialogFragment:
public class OkCancelDialogFragment extends DialogFragment {
private static final String ARG_TITLE = "title";
private static final String ARG_MESSAGE = "message";
Context context = null;
private String title;
private String message;
private boolean submitData = false;
private OkCancelDialogListener mListener;
public OkCancelDialogFragment() {
}
public static OkCancelDialogFragment newInstance(String title, String message) {
OkCancelDialogFragment fragment = new OkCancelDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
title = getArguments().getString(ARG_TITLE);
message = getArguments().getString(ARG_MESSAGE);
}
}
#Override
public Dialog onCreateDialog(Bundle saveIntsanceState){
context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View rootView = inflater.inflate(R.layout.fragment_ok_cancel_dialog, null, false);
final TextView titleView = (TextView)rootView.findViewById(R.id.tvTitle);
final TextView messView = (TextView)rootView.findViewById(R.id.tvMessage);
titleView.setText(title);
messView.setText(message);
builder.setView(rootView)
// .setTitle(title)
.setPositiveButton(R.string.ok_button_dialog_title, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = true;
if(mListener == null) mListener = (OkCancelDialogListener) context;
mListener.onFinishOkCancelDialog(submitData);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = false;
if(mListener == null) mListener = (OkCancelDialogListener) context;
mListener.onFinishOkCancelDialog(submitData);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if(mListener == null) mListener = (OkCancelDialogListener) context;
}
catch (Exception ex){
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OkCancelDialogListener {
void onFinishOkCancelDialog(boolean submit);
}
}
Please note that .setTitle(title) is valid for API 23 or higher (or maybe API 21 or higher?).
You can create your custom xml layout
and in the OnClickListener of the button you can put this :
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alertLayout = inflater.inflate(R.layout.YOUR_CUSTOM_POPUP_LAYOUT, null);
final AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setView(alertLayout);
TextView msg= alertLayout.findViewById(R.id.YOUR_TEXTVIEW_ID);
alert.show();
after that you can add another button in your popup and set a listener on it to dismiss the layout after the click.

Android: How can I make a listview wait for a variable to fill before setting?

So I have a movie trivia game that I am building. The problem I am running into is on the main user profile page I set 3 listviews. One for games where it is your turn, one for games that are waiting for your opponent, and one for completed games. These list views make calls to Parse.com to fetch the game object. In Order to fetch this info from Parse I need to provide my query with a Facebook user id. My code calls Facebook to get the ID, but the listview adapters run about 5 milliseconds before the call to Facebook returns the ID. When the user refreshes the page, the lists load properly, but when first running the app they are blank. Here is the user profile activity code:
public class UserProfileActivity extends AppCompatActivity {
ParseLogic mPl;
private WfoAdapter wfoAdapter;
private WoyAdapter woyAdapter;
private CompletedGameAdapter completedGameAdapter;
private TicketSystem mTicketsSytem;
String mMyFbId;
String mMyFbName;
int mTickets;
ListView mWfoListView;
ListView mWoyListView;
ListView mCompletedGameListView;
TextView mmTicketNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTicketsSytem = new TicketSystem();
mTickets = mTicketsSytem.getTickets();
setContentView(R.layout.activity_user_profile);
new getFbDeets().execute(); //This is where the async task is called
mPl = new ParseLogic();
mWoyListView = (ListView)findViewById(R.id.waitingForYouListView);
mWfoListView = (ListView)findViewById(R.id.waitingForOpponentListView);
mCompletedGameListView = (ListView)findViewById(R.id.completedGameListView);
mmTicketNumber = (TextView)findViewById(R.id.numberOfTickets);
mmTicketNumber.setText(String.valueOf(mTickets));
FaceBookFriends.getFaceBookFriends();
//Testing start game remove when building rest of page
Button button = (Button)findViewById(R.id.startNewGame);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserProfileActivity.this, GameStart.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
mTickets = mTicketsSytem.getTickets();
mmTicketNumber.setText(String.valueOf(mTickets));
populateWoyListView();
populateWfoListView();
populateCompleteListView();
}
#Override
public void onBackPressed(){}
#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.
//create the logout button in action bar
switch (item.getItemId()){
case R.id.logoutButton:
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser(); // this will now be null
Intent intent = new Intent(UserProfileActivity.this, WelcomeActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void populateUI() {
populateWoyListView();
populateWfoListView();
populateCompleteListView();
mWoyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String goTV = ((TextView) view.findViewById(R.id.gameObjectHiddenTextView)).getText().toString();
String score = ((TextView) view.findViewById(R.id.woyScoreNumber)).getText().toString();
Log.v("Clicked Object Id ", goTV);
Intent intent = new Intent(UserProfileActivity.this, AreYouReady.class);
intent.putExtra("Score", score);
intent.putExtra("Object Id", goTV);
startActivity(intent);
}
});
}
private void populateWoyListView() {
//mMfbId is the variable set by the facebook call
woyAdapter = new WoyAdapter(this ,mMyFbId);
woyAdapter.loadObjects();
mWoyListView.setAdapter(woyAdapter);
}
private void populateWfoListView() {
wfoAdapter = new WfoAdapter(this);
wfoAdapter.loadObjects();
mWfoListView.setAdapter(wfoAdapter);
}
private void populateCompleteListView() {
completedGameAdapter = new CompletedGameAdapter(this, mMyFbId);
completedGameAdapter.loadObjects();
mCompletedGameListView.setAdapter(completedGameAdapter);
}
protected class getFbDeets extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
mMyFbId = FaceBookFriends.getMyFbId();
mMyFbName = FaceBookFriends.getMyFbName();
Log.v("getFbDeets() ", "Is Running");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateUI();
}
}
}
This is the completed gave adapter:
/**
* Created by Tom Schinler on 9/23/2015.
*/
public class CompletedGameAdapter extends ParseQueryAdapter<Game> {
String mWinnerScore;
String mWinnerName;
String mLoserScore;
String mLoserName;
String mFbName;
public CompletedGameAdapter(Context context, final String myFbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
ParseQuery<Game> queryCreatedBy = new ParseQuery<Game>("Game");
queryCreatedBy.whereEqualTo("Created_By", ParseUser.getCurrentUser());
ParseQuery<Game> queryOppOf = new ParseQuery<Game>("Game");
queryOppOf.whereEqualTo("Opponent_Id", myFbId);
ParseQuery<Game> query = ParseQuery.or(Arrays.asList(queryCreatedBy, queryOppOf));
query.whereNotEqualTo("Creator_Score", "");
query.whereNotEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.completed_game_layout, null);
}
super.getItemView(game, view, parent);
mFbName = FaceBookFriends.getMyFbName();
TextView winOrLose = (TextView)view.findViewById(R.id.winOrLose);
int oppScore = Integer.parseInt(game.getOpponentScore());
int creatScore = Integer.parseInt(game.getCreatorScore());
if(oppScore > creatScore){
mWinnerScore = String.valueOf(oppScore);
mWinnerName = game.getOpponentName();
mLoserScore = String.valueOf(creatScore);
mLoserName = game.getCreatorFbName();
}
else {
mWinnerScore = String.valueOf(creatScore);
mWinnerName = game.getCreatorFbName();
mLoserScore = String.valueOf(oppScore);
mLoserName = game.getOpponentName();
}
TextView winnerName = (TextView)view.findViewById(R.id.winnerName);
winnerName.setText(mWinnerName);
TextView winnerScore = (TextView)view.findViewById(R.id.winnerScore);
winnerScore.setText(mWinnerScore);
TextView loserName = (TextView)view.findViewById(R.id.loserName);
loserName.setText(mLoserName);
TextView loserScore = (TextView)view.findViewById(R.id.loserScore);
loserScore.setText(mLoserScore);
if(mWinnerName.equals(mFbName)){
view.setBackgroundColor(Color.GREEN);
winOrLose.setText("WIN!!");
}
else {
view.setBackgroundColor(Color.RED);
winOrLose.setText("LOSER!!");
}
return view;
}
}
and here is the adapter that sets the listview for games waiting on the user:
/**
* Created by Tom Schinler on 9/22/2015.
*/
public class WoyAdapter extends ParseQueryAdapter<Game>{
public WoyAdapter(Context context, final String fbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
//Log.v("var fbid is ", fbId);
ParseQuery query = new ParseQuery("Game");
query.whereEqualTo("Opponent_Id", fbId);
query.whereEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.waiting_on_you_layout, null);
Log.v("WOY is this", "running");
}
super.getItemView(game, view, parent);
ProfilePictureView friendPic = (ProfilePictureView) view.findViewById(R.id.woyFbPic);
String friendId = game.getCreatorId();
if(friendId != null){
friendPic.setProfileId(friendId);
}
TextView oppName = (TextView)view.findViewById(R.id.woyNameText);
oppName.setText(game.getCreatorFbName());
TextView oppScore = (TextView)view.findViewById(R.id.woyScoreNumber);
oppScore.setText(game.getCreatorScore());
TextView GOTV = (TextView)view.findViewById(R.id.gameObjectHiddenTextView);
GOTV.setText(game.getObjectId());
return view;
}
}
I set mMyFbId with a Facebook method like this:
mMyFbId = FaceBookFriends.getMyFbId();
but it return about 1 second after the code runs to build the lists views, since they do not have the variable, they populate nothing. Please help.

Android WebView error for high density screens

I have an Android application which uses a WebView to render web page. In css I have set to show everything twice as big for high density screens (like Nexus 7 2013). If I open the web page from the browser, Everything shows as it should. But when I run the app, everything is very small.
Is there any way to determine why the application WebView shows content for lower density screens but browser (Chrome) shows as it should!
Device: Nexus 7 2013
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I think this article should help explain what you need to do: https://developers.google.com/chrome/mobile/docs/webview/pixelperfect
I suspect that the difference between Chrome and WebView boils down to the WebSettings that are being applied to the WebView.

In Android how to make my activity behave like a browser

I have two activities "Main" (with a button in it) & "Second", and I want when I click on the button in Main activity then Second activity should be launched but it should behave like a browser. Means browser should be opened when Second activity is launched.
My code is as follow:
In manifest file I have written
<activity android:name=".Second">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
In Main.java file I have written event handler like this
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, Second.class);
startActivity(intent);
}
});
First of all, is it possible what I want and if yes then am I doing it in right way? And really sorry if I my question is stupid, because I am new to Android
When I started learning about android and its intents I found it very confusing.
But category BROWSABLE in the Manifest does the following.
The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message.
Read more on: http://developer.android.com/guide/components/intents-filters.html
The two other answers opens the standard web browser and goes to the address specified. If you want a custom browser make the second activity like a web view like this example:
http://www.mkyong.com/android/android-webview-example/
Good luck!
write this in your Second activity. As your second activity will call it will open a browser.
You can also use this in onClick() also.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")));
public class WebDialog extends Dialog
{
static final int BLUE = 0xFF6D84B4;
static final float[] DIMENSIONS_DIFF_LANDSCAPE =
{ 20, 60 };
static final float[] DIMENSIONS_DIFF_PORTRAIT =
{ 40, 60 };
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
static final String DISPLAY_STRING = "touch";
private String mUrl;
// private DialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
public WebDialog(Context context, String url)
{
super(context);
mUrl = url;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
int orientation = getContext().getResources().getConfiguration().orientation;
float[] dimensions = (orientation == Configuration.ORIENTATION_LANDSCAPE) ? DIMENSIONS_DIFF_LANDSCAPE : DIMENSIONS_DIFF_PORTRAIT;
addContentView(mContent, new LinearLayout.LayoutParams(display.getWidth() - ((int) (dimensions[0] * scale + 0.5f)), display.getHeight() - ((int) (dimensions[1] * scale + 0.5f))));
}
private void setUpTitle()
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.ic_launcher);
mTitle = new TextView(getContext());
mTitle.setText("Website");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(BLUE);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
// mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
// mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView()
{
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new WebDialog.DialogWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
System.out.println(" mURL = "+mUrl);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class DialogWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
WebDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0)
{
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}
Seems like you are trying to open a browser to a specific page when the button is clicked on the Main acitvity.
If that is the case you don't need the Second activity, you just need to do something like this:
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(i);
}
}

Android soft Keyboard not open in webView`

I m Using WebView in AlertDialog to authenticate user to twitter.
but When i click on field in webview ,android keyboard doesnt open.
here is my code that shows how i added webview in alert dialog.
i implicitly call android keyboard but it open keyboard behind alert dialog.
here is my code.
public static void webViewDialog(final String authorizationURL, final int type)
{
final boolean correctPin;
System.out.println("In webViewDialog");
container = new LinearLayout(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(context);
webView.setMinimumWidth(200);
webView.requestFocusFromTouch();
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new TwitterWebViewClient());
webView.loadUrl(authorizationURL);
webView.setBackgroundColor(0xFFbbd7e9);
container.addView(webView);
Builder webDialog = new AlertDialog.Builder(context);
webDialog.setView(container).setTitle("Twitter Login")
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
if (type == 0)
{
twitterPinCodeDialog();
dialog.dismiss();
}
}
}).show();
showVirtualKeyboard();
}
public static void showVirtualKeyboard()
{
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
InputMethodManager m = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if(m != null)
{
// m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
m.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 100);
}
Here is my solution to this problem:
Put a dummy edit text, and set it's visibility to GONE, and add it to a containing LinearLayout, after adding the WebView to the layout.
Example:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LinearLayout wrapper = new LinearLayout(this);
WebView webView = new WebView(this);
EditText keyboardHack = new EditText(this);
keyboardHack.setVisibility(View.GONE);
webView.loadUrl(url);
wrapper.setOrientation(LinearLayout.VERTICAL);
wrapper.addView(webView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
wrapper.addView(keyboardHack, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
builder.setView(wrapper);
builder.create().show();
Once this is done, everything should work properly, and when you select an item in the WebView, the keyboard appears as expected.
I am using a PopupWindow with a WebView inside it and experienced the same problem, but if I set focusable to true in the parent the problem goes away:
popupWindow.setFocusable(true);
Hope this helps!
I had a similar issue and solved it in this way:
I override the onCreateView() method on the dialog fragment and define all view stuff configuration for my web view.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
// do some config
// some other stuffs
loginpage.loadUrl(url);
return view;
}
On the onCreateDialog() method i just add these.
#Override
public Dialog onCreateDialog(Bundle savedInstaceState) {
Dialog dialog = super.onCreateDialog(savedInstaceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
In my case i wanted to show a dialog with no title. So due the DialogBuilder take care of creating dialog's view i decided to override the onCreateView() and just call the super.onCreateDialog() and add my window configuration.
I also suffer from this problem, I solved this problem by customizing Dialog, here is my custom dialog code, hope so this is use full for you.
TwitterDialog fb=new TwitterDialog(this);
fb.abc();
//fb.dismiss();
class TwitterDialog extends Dialog {
Context context;
String url="https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2";
public TwitterDialog(Context context) {
super(context);
this.context=context;
}
void abc(){
LinearLayout mContent = new LinearLayout(context);
mContent.setOrientation(LinearLayout.VERTICAL);
final float scale = context.getResources().getDisplayMetrics().density;
float[] dimensions =new float[]{400.0f,500.0f};
addContentView(mContent, new FrameLayout.LayoutParams(
(int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
FrameLayout.LayoutParams FILL =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
WebView mWebView = new WebView(context);
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new WebClicent());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
TwitterDialog.this.show();
}
class WebClicent extends WebViewClient{
#Override
public void onLoadResource(WebView view, String url) {
System.out.println("onLoadResource "+url);
super.onLoadResource(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("onPageFinished "+url);
//TwitterDialog.this.dismiss();
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("onPageStarted "+url);
super.onPageStarted(view, url, favicon);
}
}
}//TWitterDialog
The reason your keyboard may not be showing up, is probably because you are using a device that already has a hard keyboard. ANY DEVICE WITH A PHYSICAL KEYBOARD does not need to show a soft keyboard... That is why it is not showing. Because your device or your emulator has a physical hard keyboard.

Categories

Resources