目的:在学习自定义控件过程中,想把一个WebView嵌入到RelativeLayout中,然后使用loadURL加载某URL!
实现:
package com.study.test;
public class myWebView extends RelativeLayout
{
public myWebView(Context context)
{
this(context, null, 0);
}
public myWebView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public myWebView(Context context, AttributeSet attrs, int defStyle)
{
if (uiThreadHandler == null)
{
uiThreadHandler = new Handler();
}
new Thread()
{
public void run()
{
try
{
// Get a URL from server.
Context context = getContext();
String newURL = GetNewURL(context);
if (newURL != null) // we get an URL back
{
synchronized(this)
{
// Create a view for the URL.
Looper.prepare();
final WebView newWebView = new WebView ( context);
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 48);
newWebView.setLayoutParams(params);
newWebView.loadUrl(newURL );
// Force this view to show the webview
uiThreadHandler.post(new Runnable()
{
public void run()
{
try
{
addView(newWebView);
}
catch (Exception e)
{
}
finally
{
}
}
});
}
}
}
}
catch (Exception e)
{
}
}
}.start();
}
}
在应用的main.xml添加如下内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.study.test.myWebView
android:id="@+id/myWeb"
android:layout_width="fill_parent"