In Android how to make my activity behave like a browser - android

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);
}
}

Related

how to control textView onclicklistener with autolink web setting or in other words,intercept autolink web OnClick event?

How to control textView onclicklistener with autolink web setting or in other words,intercept autolink web OnClick event?
For example,String text="Lucy is very nice.Here is her link.https://www.google.com";textview.setText(text);
when clicking "https://www.google.com",I can catch it and jump to my app activity not to web browser.
Textview has a property “autolink”.I set autolink as web.android:autoLink="web" So,android system can automatically detect the url.When clicking the url,it will jump to the browser.Now when clicking, I do not want jump to the brower,I just want to jump to my app activity and stay in app.
Thanks you for all of your answers.Now I find my question's answer.There are two steps.
1.you need set Textview property. android:autoLink="web"
<TextView
android:id="#+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="Lucy is very nice.Here is her link.https://www.google.com" />
2.override URL onclick.There is an example.
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
CharSequence text = tv.getText();
if (text instanceof Spannable) {
int end = text.length();
Spannable sp = (Spannable) text;
URLSpan urls[] = sp.getSpans(0, end, URLSpan.class);
SpannableStringBuilder style = new SpannableStringBuilder(text);
style.clearSpans();
for (URLSpan urlSpan : urls) {
MyURLSpan myURLSpan = new MyURLSpan(urlSpan.getURL());
style.setSpan(myURLSpan, sp.getSpanStart(urlSpan),
sp.getSpanEnd(urlSpan),
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
tv.setText(style);
}
}
private class MyURLSpan extends ClickableSpan {
private String url;
public MyURLSpan(String url) {
this.url = url;
}
#Override
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
}
}
}
3.The above code perfectly solved my problem.So when I click www.google.com in the Textview,the url will show out and jump to a specific activity.
As your question is not clear I am giving you answer that might help.
Create another activity i which you want to show the link :
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_search);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString("message");
wv=(WebView)findViewById(R.id.left_webview);
getActionBar().setHomeButtonEnabled(true);
//wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setSupportMultipleWindows(true);
wv.loadUrl(url);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("URL :: " + url);
view.loadUrl(url);
return true;
}
});
}
in the textView activity :
Intent i = new Intent(TextViewActivity.this,NextActivity.class);
i.putExtra("message","https://google.com");
startActivity(i);
If I understand you question correctly this is what you are looking for. In order to control the click event on the text inside the TextView you have to use HTML to create the link and use a SpannableString.
// textView.setText("Lucy is very nice. Here is her link. https://www.google.com");
final String source = "Lucy is very nice. Here is her link. Click";
final Spanned html = Html.fromHtml(source);
final SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(html);
final URLSpan[] spans = spannableStringBuilder.getSpans(0, html.length(), URLSpan.class);
final URLSpan span = spans[0];
final int start = spannableStringBuilder.getSpanStart(span);
final int end = spannableStringBuilder.getSpanEnd(span);
final int flags = spannableStringBuilder.getSpanFlags(span);
final ClickableSpan clickableSpan = new ClickableSpan() {
public void onClick(View view) {
Log.d(TAG, "Clicked: " + span.getURL());
}
};
spannableStringBuilder.setSpan(clickableSpan, start, end, flags);
spannableStringBuilder.removeSpan(span);
textView.setText(spannableStringBuilder);
textView.setLinksClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
EDIT
So, according to your comment you can't use HTML so here is another example taking the text from the TextView with autoLink already set:
final TextView textView = (TextView) findViewById(R.id.text);
final CharSequence text = textView.getText();
final SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
final URLSpan[] spans = spannableStringBuilder.getSpans(0, text.length(), URLSpan.class);
final URLSpan span = spans[0];
final int start = spannableStringBuilder.getSpanStart(span);
final int end = spannableStringBuilder.getSpanEnd(span);
final int flags = spannableStringBuilder.getSpanFlags(span);
final ClickableSpan clickableSpan = new ClickableSpan() {
public void onClick(View view) {
Log.d(TAG, "Clicked: " + span.getURL());
}
};
spannableStringBuilder.setSpan(clickableSpan, start, end, flags);
spannableStringBuilder.removeSpan(span);
textView.setText(spannableStringBuilder);
textView.setLinksClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
I don't get what you are trying to say, but this will open a URL, or you can copy it to the cliopboard like copy and paste.
button.setOnClickListener((View.OnClickListener) v -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
}

Set dynamically created TextView on frame layout

I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")

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.

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.

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

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);
}
}
}

Categories

Resources