PyGobject(一百零四)CSS系列——在TextView中显示样式,可修改

例子

这里写图片描述

代码:

#!/usr/bin/env python3
# section 154
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2013 Gian Mario Tagliaretti <gianmt@gnome.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
# USA

TITLE = "CSS Basics"
DESCRIPTION = """
Gtk themes are written using CSS. Every widget is build of multiple items
that you can style very similarly to a regular website.
"""

import os
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango, Gio, GLib


class CSSBasicsApp:
    def __init__(self):
        #: Store the last successful parsing of the css so we can revert
        #: this in case of an error.
        self.last_good_text = ''
        #: Set when we receive a parsing-error callback. This is needed
        #: to handle logic after a parsing-error callback which does not raise
        #: an exception with provider.load_from_data()
        self.last_error_code = 0

        self.window = Gtk.Window()
        self.window.set_title('CSS Basics')
        self.window.set_default_size(400, 300)
        self.window.set_border_width(10)
        self.window.connect('destroy', lambda w: Gtk.main_quit())

        self.infobar = Gtk.InfoBar()
        self.infolabel = Gtk.Label()
        self.infobar.get_content_area().pack_start(self.infolabel, False, False, 0)
        self.infobar.set_message_type(Gtk.MessageType.WARNING)

        scrolled = Gtk.ScrolledWindow()
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        box.pack_start(scrolled, expand=True, fill=True, padding=0)
        box.pack_start(self.infobar, expand=False, fill=True, padding=0)
        self.window.add(box)

        provider = Gtk.CssProvider()

        buffer = Gtk.TextBuffer()
        buffer.create_tag(tag_name="warning", underline=Pango.Underline.SINGLE)
        buffer.create_tag(tag_name="error", underline=Pango.Underline.ERROR)
        buffer.connect("changed", self.css_text_changed, provider)

        provider.connect("parsing-error", self.show_parsing_error, buffer)

        textview = Gtk.TextView()
        textview.set_buffer(buffer)
        scrolled.add(textview)

        bytes = Gio.resources_lookup_data("/css/css_basics.css", 0)
        buffer.set_text(bytes.get_data().decode('utf-8'))

        self.apply_css(self.window, provider)
        self.window.show_all()
        self.infobar.hide()

    def apply_css(self, widget, provider):
        Gtk.StyleContext.add_provider(widget.get_style_context(),
                                      provider,
                                      Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        if isinstance(widget, Gtk.Container):
            widget.forall(self.apply_css, provider)

    def show_parsing_error(self, provider, section, error, buffer):
        start = buffer.get_iter_at_line_index(section.get_start_line(),
                                              section.get_start_position())

        end = buffer.get_iter_at_line_index(section.get_end_line(),
                                            section.get_end_position())

        if error.code == Gtk.CssProviderError.DEPRECATED:
            tag_name = "warning"
        else:
            tag_name = "error"
        self.last_error_code = error.code

        self.infolabel.set_text(error.message)
        self.infobar.show_all()

        buffer.apply_tag_by_name(tag_name, start, end)

    def css_text_changed(self, buffer, provider):
        start = buffer.get_start_iter()
        end = buffer.get_end_iter()
        buffer.remove_all_tags(start, end)

        text = buffer.get_text(start, end, False).encode('utf-8')

        # Ignore CSS errors as they are shown by highlighting
        try:
            provider.load_from_data(text)
        except GLib.GError as e:
            if e.domain != 'gtk-css-provider-error-quark':
                raise e

        # If the parsing-error callback is ever run (even in the case of warnings)
        # load the last good css text that ran without any warnings. Otherwise
        # we may have a discrepancy in "last_good_text" vs the current buffer
        # causing section.get_start_position() to give back an invalid position
        # for the editor buffer.
        if self.last_error_code:
            provider.load_from_data(self.last_good_text)
            self.last_error_code = 0
        else:
            self.last_good_text = text
            self.infobar.hide()

        Gtk.StyleContext.reset_widgets(Gdk.Screen.get_default())


def main():
    CSSBasicsApp()
    Gtk.main()


if __name__ == '__main__':
    base_path = os.path.abspath(os.path.dirname(__file__))
    resource_path = os.path.join(base_path, '../Data/demo.gresource')
    resource = Gio.Resource.load(resource_path)
    Gio.resources_register(resource)
    main()

css_basics.css

/* You can edit the text in this window to change the
 * appearance of this Window.
 * Be careful, if you screw it up, nothing might be visible
 * anymore. :)
 */
/* This CSS resets all properties to their defaults values
 *    and overrides all user settings and the theme in use */
@import url("resource://css/css_reset.css");

/*设置默认的颜色,字体和边框*/
* {
    color: green;
    font-family: Monospace;
    border: 1px solid;
}

/* 设置选中文本的颜色和背景颜色 */
selection {
    background-color: darkGreen;
    color: green;
}

代码解析:
跟上一个例子有所不同的是,这个代码使用一个TextView来显示css文件,并监听文本内容的改变,当文本内容改变时,使用
provider.load_from_data(text)重新加载CSS样式,当加载错误出现错误就会调用show_parsing_error()方法显示错误信息

provider.connect("parsing-error", self.show_parsing_error, buffer)





代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
若要在Android Studio的TextView显示从网页抓取的数据,可以使用HttpURLConnection或者OkHttp等网络库来获取网页内容。获取到网页内容后,再将其设置到TextView即可。 以下是一个简单的示例代码,可以获取指定URL的网页内容,并将其显示TextView: ``` // 找到 TextView 控件 TextView textView = findViewById(R.id.textView); // 创建一个新的线程来获取网页内容 new Thread(new Runnable() { @Override public void run() { try { // 创建 URL 对象 URL url = new URL("https://www.google.com"); // 创建 HttpURLConnection 对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法和超时时间 connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // 获取网页内容 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } String content = stringBuilder.toString(); // 在 TextView 显示网页内容 runOnUiThread(new Runnable() { @Override public void run() { textView.setText(content); } }); } catch (IOException e) { e.printStackTrace(); } } }).start(); ``` 上述代码,我们首先找到了一个TextView控件,然后创建了一个新的线程来获取网页内容。在该线程,我们使用HttpURLConnection来获取指定URL的网页内容,然后将其设置到TextView。注意,由于网络请求需要在子线程进行,我们需要使用runOnUiThread方法来在主线程更新UI。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sanxiaochengyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值