WebView

Struct WebView 

Source
pub struct WebView { /* private fields */ }
Expand description

WebView 组件,用于显示网页内容

Implementations§

Source§

impl WebView

Source

pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self>

创建一个新的 WebView

§参数
  • activity: Activity 引用
  • parent: 可选的父视图ID
§示例
let webview = WebView::new(&mut activity, Some(layout_id))?;
Source

pub fn id(&self) -> i64

获取视图ID

Source

pub fn view(&self) -> &View

获取视图引用

Examples found in repository?
examples/webview_demo_v2.rs (line 46)
12fn main() -> Result<()> {
13    println!("=== WebView 网页视图演示 (新库版本) ===\n");
14    
15    // 创建 Activity
16    let mut activity = Activity::new(false)?;
17    println!("✓ 连接建立\n");
18    
19    // 创建根布局 (垂直)
20    let root = activity.create_linear_layout(None)?;
21    
22    // 标题文本
23    let title = activity.create_text_view("🌐 WebView 演示", Some(root.id()))?;
24    title.set_text_size(&mut activity, 20)?;
25    title.view().set_height_wrap_content(&mut activity)?;
26    title.view().set_margin(&mut activity, 16)?;
27    title.view().set_linear_layout_params(&mut activity, 0, None)?;
28    
29    // 提示文本
30    let hint = activity.create_text_view(
31        "━━━━━━━━━━━━━━━━━━━━━━\n\
32        演示步骤:\n\
33        1️⃣ 显示HTML内容 (3秒)\n\
34        2️⃣ 加载Google网页 (3秒)\n\
35        3️⃣ 请求JavaScript权限\n\
36        4️⃣ 执行JavaScript代码\n\
37        ━━━━━━━━━━━━━━━━━━━━━━", 
38        Some(root.id()))?;
39    hint.set_text_size(&mut activity, 14)?;
40    hint.view().set_height_wrap_content(&mut activity)?;
41    hint.view().set_margin(&mut activity, 16)?;
42    hint.view().set_linear_layout_params(&mut activity, 0, None)?;
43    
44    // 创建 WebView
45    let webview = activity.create_web_view(Some(root.id()))?;
46    webview.view().set_linear_layout_params(&mut activity, 1, None)?;  // 占据剩余空间
47    
48    println!("✓ 界面创建完成\n");
49    
50    // 演示流程
51    demo_workflow(&mut activity, &webview)?;
52    
53    println!("\n📌 等待用户关闭窗口...");
54    
55    // 事件循环
56    loop {
57        let event = read_message(activity.event_stream())?;
58        let event_type = event["type"].as_str().unwrap_or("");
59        
60        match event_type {
61            "destroy" => {
62                println!("\n✓ Activity 已关闭");
63                return Ok(());
64            },
65            _ => {}
66        }
67    }
68}
Source

pub fn load_uri(&self, activity: &mut Activity, uri: &str) -> Result<()>

加载URI/URL

§参数
  • activity: Activity 引用
  • uri: 要加载的URL,例如 “https://www.google.com”
§示例
webview.load_uri(&mut activity, "https://www.google.com")?;
Examples found in repository?
examples/webview_demo_v2.rs (line 120)
71fn demo_workflow(activity: &mut Activity, webview: &WebView) -> Result<()> {
72    use std::thread;
73    use std::time::Duration;
74    
75    // 步骤1: 显示 HTML 内容
76    println!("1️⃣ 显示 HTML 内容...");
77    let html = r#"
78        <html>
79        <head>
80            <meta name="viewport" content="width=device-width, initial-scale=1.0">
81            <style>
82                body {
83                    font-family: Arial, sans-serif;
84                    padding: 20px;
85                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
86                    color: white;
87                    text-align: center;
88                }
89                h1 {
90                    font-size: 2em;
91                    margin-bottom: 20px;
92                    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
93                }
94                p {
95                    font-size: 1.2em;
96                    line-height: 1.6;
97                }
98                .emoji {
99                    font-size: 3em;
100                    margin: 20px 0;
101                }
102            </style>
103        </head>
104        <body>
105            <div class="emoji">🚀</div>
106            <h1>Hello from HTML!</h1>
107            <p>这是通过 setData() 设置的 HTML 内容</p>
108            <p>包含样式和布局</p>
109        </body>
110        </html>
111    "#;
112    webview.set_data(activity, html)?;
113    println!("   ✓ HTML 内容已设置");
114    
115    // 等待3秒
116    thread::sleep(Duration::from_secs(3));
117    
118    // 步骤2: 加载网页
119    println!("\n2️⃣ 加载 Google 网页...");
120    webview.load_uri(activity, "https://www.google.com")?;
121    println!("   ✓ URL 已加载");
122    
123    // 等待3秒
124    thread::sleep(Duration::from_secs(3));
125    
126    // 步骤3: 请求 JavaScript 权限
127    println!("\n3️⃣ 请求 JavaScript 权限...");
128    println!("   ⏳ 等待用户确认...");
129    
130    match webview.allow_javascript(activity, true) {
131        Ok(enabled) => {
132            if enabled {
133                println!("   ✓ JavaScript 已启用");
134                
135                // 步骤4: 执行 JavaScript
136                println!("\n4️⃣ 执行 JavaScript 代码...");
137                let js_code = r#"
138                    document.body.innerHTML = `
139                        <div style="
140                            font-family: Arial, sans-serif;
141                            padding: 20px;
142                            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
143                            color: white;
144                            text-align: center;
145                            min-height: 100vh;
146                            display: flex;
147                            flex-direction: column;
148                            justify-content: center;
149                            align-items: center;
150                        ">
151                            <div style="font-size: 4em; margin-bottom: 20px;">✨</div>
152                            <h1 style="font-size: 2.5em; margin-bottom: 20px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">
153                                Hello from JavaScript!
154                            </h1>
155                            <p style="font-size: 1.5em; line-height: 1.6;">
156                                这个页面是通过 evaluateJS() 动态创建的
157                            </p>
158                            <p style="font-size: 1.2em; margin-top: 20px;">
159                                🎉 JavaScript 执行成功!
160                            </p>
161                        </div>
162                    `;
163                "#;
164                webview.evaluate_js(activity, js_code)?;
165                println!("   ✓ JavaScript 已执行");
166                println!("   ✓ 页面内容已通过 JS 更新");
167            } else {
168                println!("   ⚠ JavaScript 未启用(用户拒绝或系统限制)");
169            }
170        },
171        Err(e) => {
172            println!("   ⚠ 启用 JavaScript 失败: {}", e);
173        }
174    }
175    
176    println!("\n✓ 演示流程完成!");
177    
178    Ok(())
179}
Source

pub fn set_data(&self, activity: &mut Activity, data: &str) -> Result<()>

设置HTML内容

§参数
  • activity: Activity 引用
  • data: HTML文档内容
§示例
webview.set_data(&mut activity, "<html><body><h1>Hello</h1></body></html>")?;
Examples found in repository?
examples/webview_demo_v2.rs (line 112)
71fn demo_workflow(activity: &mut Activity, webview: &WebView) -> Result<()> {
72    use std::thread;
73    use std::time::Duration;
74    
75    // 步骤1: 显示 HTML 内容
76    println!("1️⃣ 显示 HTML 内容...");
77    let html = r#"
78        <html>
79        <head>
80            <meta name="viewport" content="width=device-width, initial-scale=1.0">
81            <style>
82                body {
83                    font-family: Arial, sans-serif;
84                    padding: 20px;
85                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
86                    color: white;
87                    text-align: center;
88                }
89                h1 {
90                    font-size: 2em;
91                    margin-bottom: 20px;
92                    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
93                }
94                p {
95                    font-size: 1.2em;
96                    line-height: 1.6;
97                }
98                .emoji {
99                    font-size: 3em;
100                    margin: 20px 0;
101                }
102            </style>
103        </head>
104        <body>
105            <div class="emoji">🚀</div>
106            <h1>Hello from HTML!</h1>
107            <p>这是通过 setData() 设置的 HTML 内容</p>
108            <p>包含样式和布局</p>
109        </body>
110        </html>
111    "#;
112    webview.set_data(activity, html)?;
113    println!("   ✓ HTML 内容已设置");
114    
115    // 等待3秒
116    thread::sleep(Duration::from_secs(3));
117    
118    // 步骤2: 加载网页
119    println!("\n2️⃣ 加载 Google 网页...");
120    webview.load_uri(activity, "https://www.google.com")?;
121    println!("   ✓ URL 已加载");
122    
123    // 等待3秒
124    thread::sleep(Duration::from_secs(3));
125    
126    // 步骤3: 请求 JavaScript 权限
127    println!("\n3️⃣ 请求 JavaScript 权限...");
128    println!("   ⏳ 等待用户确认...");
129    
130    match webview.allow_javascript(activity, true) {
131        Ok(enabled) => {
132            if enabled {
133                println!("   ✓ JavaScript 已启用");
134                
135                // 步骤4: 执行 JavaScript
136                println!("\n4️⃣ 执行 JavaScript 代码...");
137                let js_code = r#"
138                    document.body.innerHTML = `
139                        <div style="
140                            font-family: Arial, sans-serif;
141                            padding: 20px;
142                            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
143                            color: white;
144                            text-align: center;
145                            min-height: 100vh;
146                            display: flex;
147                            flex-direction: column;
148                            justify-content: center;
149                            align-items: center;
150                        ">
151                            <div style="font-size: 4em; margin-bottom: 20px;">✨</div>
152                            <h1 style="font-size: 2.5em; margin-bottom: 20px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">
153                                Hello from JavaScript!
154                            </h1>
155                            <p style="font-size: 1.5em; line-height: 1.6;">
156                                这个页面是通过 evaluateJS() 动态创建的
157                            </p>
158                            <p style="font-size: 1.2em; margin-top: 20px;">
159                                🎉 JavaScript 执行成功!
160                            </p>
161                        </div>
162                    `;
163                "#;
164                webview.evaluate_js(activity, js_code)?;
165                println!("   ✓ JavaScript 已执行");
166                println!("   ✓ 页面内容已通过 JS 更新");
167            } else {
168                println!("   ⚠ JavaScript 未启用(用户拒绝或系统限制)");
169            }
170        },
171        Err(e) => {
172            println!("   ⚠ 启用 JavaScript 失败: {}", e);
173        }
174    }
175    
176    println!("\n✓ 演示流程完成!");
177    
178    Ok(())
179}
Source

pub fn allow_javascript( &self, activity: &mut Activity, allow: bool, ) -> Result<bool>

允许JavaScript执行

如果请求允许JavaScript,会弹出用户确认对话框,用户可以拒绝。 此方法会阻塞直到用户响应。

§参数
  • activity: Activity 引用
  • allow: 是否允许JavaScript
§返回

返回调用后JavaScript是否启用

Examples found in repository?
examples/webview_demo_v2.rs (line 130)
71fn demo_workflow(activity: &mut Activity, webview: &WebView) -> Result<()> {
72    use std::thread;
73    use std::time::Duration;
74    
75    // 步骤1: 显示 HTML 内容
76    println!("1️⃣ 显示 HTML 内容...");
77    let html = r#"
78        <html>
79        <head>
80            <meta name="viewport" content="width=device-width, initial-scale=1.0">
81            <style>
82                body {
83                    font-family: Arial, sans-serif;
84                    padding: 20px;
85                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
86                    color: white;
87                    text-align: center;
88                }
89                h1 {
90                    font-size: 2em;
91                    margin-bottom: 20px;
92                    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
93                }
94                p {
95                    font-size: 1.2em;
96                    line-height: 1.6;
97                }
98                .emoji {
99                    font-size: 3em;
100                    margin: 20px 0;
101                }
102            </style>
103        </head>
104        <body>
105            <div class="emoji">🚀</div>
106            <h1>Hello from HTML!</h1>
107            <p>这是通过 setData() 设置的 HTML 内容</p>
108            <p>包含样式和布局</p>
109        </body>
110        </html>
111    "#;
112    webview.set_data(activity, html)?;
113    println!("   ✓ HTML 内容已设置");
114    
115    // 等待3秒
116    thread::sleep(Duration::from_secs(3));
117    
118    // 步骤2: 加载网页
119    println!("\n2️⃣ 加载 Google 网页...");
120    webview.load_uri(activity, "https://www.google.com")?;
121    println!("   ✓ URL 已加载");
122    
123    // 等待3秒
124    thread::sleep(Duration::from_secs(3));
125    
126    // 步骤3: 请求 JavaScript 权限
127    println!("\n3️⃣ 请求 JavaScript 权限...");
128    println!("   ⏳ 等待用户确认...");
129    
130    match webview.allow_javascript(activity, true) {
131        Ok(enabled) => {
132            if enabled {
133                println!("   ✓ JavaScript 已启用");
134                
135                // 步骤4: 执行 JavaScript
136                println!("\n4️⃣ 执行 JavaScript 代码...");
137                let js_code = r#"
138                    document.body.innerHTML = `
139                        <div style="
140                            font-family: Arial, sans-serif;
141                            padding: 20px;
142                            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
143                            color: white;
144                            text-align: center;
145                            min-height: 100vh;
146                            display: flex;
147                            flex-direction: column;
148                            justify-content: center;
149                            align-items: center;
150                        ">
151                            <div style="font-size: 4em; margin-bottom: 20px;">✨</div>
152                            <h1 style="font-size: 2.5em; margin-bottom: 20px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">
153                                Hello from JavaScript!
154                            </h1>
155                            <p style="font-size: 1.5em; line-height: 1.6;">
156                                这个页面是通过 evaluateJS() 动态创建的
157                            </p>
158                            <p style="font-size: 1.2em; margin-top: 20px;">
159                                🎉 JavaScript 执行成功!
160                            </p>
161                        </div>
162                    `;
163                "#;
164                webview.evaluate_js(activity, js_code)?;
165                println!("   ✓ JavaScript 已执行");
166                println!("   ✓ 页面内容已通过 JS 更新");
167            } else {
168                println!("   ⚠ JavaScript 未启用(用户拒绝或系统限制)");
169            }
170        },
171        Err(e) => {
172            println!("   ⚠ 启用 JavaScript 失败: {}", e);
173        }
174    }
175    
176    println!("\n✓ 演示流程完成!");
177    
178    Ok(())
179}
Source

pub fn allow_content_uri( &self, activity: &mut Activity, allow: bool, ) -> Result<()>

允许从 content:// URI 加载内容

§参数
  • activity: Activity 引用
  • allow: 是否允许
Source

pub fn allow_navigation( &self, activity: &mut Activity, allow: bool, ) -> Result<()>

允许导航到不同站点

§参数
  • activity: Activity 引用
  • allow: 是否允许用户和JavaScript导航到不同站点
Source

pub fn evaluate_js(&self, activity: &mut Activity, code: &str) -> Result<()>

在WebView中执行JavaScript代码

需要先通过 allow_javascript() 启用JavaScript。

§参数
  • activity: Activity 引用
  • code: 要执行的JavaScript代码
§示例
webview.evaluate_js(&mut activity, "alert('Hello from JavaScript!');")?;
Examples found in repository?
examples/webview_demo_v2.rs (line 164)
71fn demo_workflow(activity: &mut Activity, webview: &WebView) -> Result<()> {
72    use std::thread;
73    use std::time::Duration;
74    
75    // 步骤1: 显示 HTML 内容
76    println!("1️⃣ 显示 HTML 内容...");
77    let html = r#"
78        <html>
79        <head>
80            <meta name="viewport" content="width=device-width, initial-scale=1.0">
81            <style>
82                body {
83                    font-family: Arial, sans-serif;
84                    padding: 20px;
85                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
86                    color: white;
87                    text-align: center;
88                }
89                h1 {
90                    font-size: 2em;
91                    margin-bottom: 20px;
92                    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
93                }
94                p {
95                    font-size: 1.2em;
96                    line-height: 1.6;
97                }
98                .emoji {
99                    font-size: 3em;
100                    margin: 20px 0;
101                }
102            </style>
103        </head>
104        <body>
105            <div class="emoji">🚀</div>
106            <h1>Hello from HTML!</h1>
107            <p>这是通过 setData() 设置的 HTML 内容</p>
108            <p>包含样式和布局</p>
109        </body>
110        </html>
111    "#;
112    webview.set_data(activity, html)?;
113    println!("   ✓ HTML 内容已设置");
114    
115    // 等待3秒
116    thread::sleep(Duration::from_secs(3));
117    
118    // 步骤2: 加载网页
119    println!("\n2️⃣ 加载 Google 网页...");
120    webview.load_uri(activity, "https://www.google.com")?;
121    println!("   ✓ URL 已加载");
122    
123    // 等待3秒
124    thread::sleep(Duration::from_secs(3));
125    
126    // 步骤3: 请求 JavaScript 权限
127    println!("\n3️⃣ 请求 JavaScript 权限...");
128    println!("   ⏳ 等待用户确认...");
129    
130    match webview.allow_javascript(activity, true) {
131        Ok(enabled) => {
132            if enabled {
133                println!("   ✓ JavaScript 已启用");
134                
135                // 步骤4: 执行 JavaScript
136                println!("\n4️⃣ 执行 JavaScript 代码...");
137                let js_code = r#"
138                    document.body.innerHTML = `
139                        <div style="
140                            font-family: Arial, sans-serif;
141                            padding: 20px;
142                            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
143                            color: white;
144                            text-align: center;
145                            min-height: 100vh;
146                            display: flex;
147                            flex-direction: column;
148                            justify-content: center;
149                            align-items: center;
150                        ">
151                            <div style="font-size: 4em; margin-bottom: 20px;">✨</div>
152                            <h1 style="font-size: 2.5em; margin-bottom: 20px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">
153                                Hello from JavaScript!
154                            </h1>
155                            <p style="font-size: 1.5em; line-height: 1.6;">
156                                这个页面是通过 evaluateJS() 动态创建的
157                            </p>
158                            <p style="font-size: 1.2em; margin-top: 20px;">
159                                🎉 JavaScript 执行成功!
160                            </p>
161                        </div>
162                    `;
163                "#;
164                webview.evaluate_js(activity, js_code)?;
165                println!("   ✓ JavaScript 已执行");
166                println!("   ✓ 页面内容已通过 JS 更新");
167            } else {
168                println!("   ⚠ JavaScript 未启用(用户拒绝或系统限制)");
169            }
170        },
171        Err(e) => {
172            println!("   ⚠ 启用 JavaScript 失败: {}", e);
173        }
174    }
175    
176    println!("\n✓ 演示流程完成!");
177    
178    Ok(())
179}
Source

pub fn go_back(&self, activity: &mut Activity) -> Result<()>

后退到历史记录的上一页

Source

pub fn go_forward(&self, activity: &mut Activity) -> Result<()>

前进到历史记录的下一页

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V