PyGobject(三十七)布局容器之Dialog

Gtk.Dialog

Gtk.Dialog弹出式对话框,有多个子类,如文件选择器,颜色选择器,字体选择器等等,使用这些子类相当的方便。当然你也可以继承Dialog类,自定义属于自己的对话框。

继承关系

Gtk.Dialog是Gtk.Window的直接子类
这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
add_action_widget (child, response_id)
add_button (button_text, response_id)
add_buttons (*args)
get_action_area ()
get_content_area ()
get_header_bar ()
get_response_for_widget (widget)
get_widget_for_response (response_id)
response (response_id)
run ()
set_alternative_button_order_from_array (new_order)
set_default_response (response_id)
set_response_sensitive (response_id, setting)

Virtual Methods

do_close ()
do_response (response_id)

Properties

NameTypeFlagsShort Description
use-header-barintr/w/coUse Header Bar for actions.

Signals

NameShort Description
closeThe ::close signal is a keybinding signal which gets emitted
when the user uses a keybinding to close the dialog.
responseEmitted when an action widget is clicked, the dialog receives a
delete event, or the application programmer calls Gtk.Dialog.response().

Gtk.MessageDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
format_secondary_markup (message_format)
format_secondary_text (message_format)
get_image ()
get_message_area ()
set_image (image)
set_markup (str)

Properties

NameTypeFlagsShort Description
buttonsGtk.ButtonsTypew/coThe buttons shown in the message dialog
imageGtk.Widgetd/r/wThe image deprecated
message-areaGtk.WidgetrGtk.VBox that holds the dialog’s primary and secondary labels
message-typeGtk.MessageTyper/w/c/enThe type of message
secondary-textstrr/wThe secondary text of the message dialog
secondary-use-markupboolr/w/enThe secondary text includes Pango markup.
textstrr/wThe primary text of the message dialog
use-markupboolr/w/enThe primary text of the title includes Pango markup.

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/16
# section 045
TITLE = "MessageDialog"
DESCRIPTION = """
Gtk.MessageDialog presents a dialog with some message text.
It’s simply a convenience widget; you could construct the equivalent of Gtk.MessageDialog
from Gtk.Dialog without too much effort, but Gtk.MessageDialog saves typing.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class MessageDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="MessageDialog Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Information")
        button1.connect("clicked", self.on_info_clicked)
        box.add(button1)

        button2 = Gtk.Button("Error")
        button2.connect("clicked", self.on_error_clicked)
        box.add(button2)

        button3 = Gtk.Button("Warning")
        button3.connect("clicked", self.on_warn_clicked)
        box.add(button3)

        button4 = Gtk.Button("Question")
        button4.connect("clicked", self.on_question_clicked)
        box.add(button4)

    def on_info_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
                                   Gtk.ButtonsType.OK, "This is an INFO MessageDialog")
        dialog.format_secondary_text(
                "And this is the secondary text that explains things.")
        dialog.run()
        print("INFO dialog closed")

        dialog.destroy()

    def on_error_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
                                   Gtk.ButtonsType.CANCEL, "This is an ERROR MessageDialog")
        dialog.format_secondary_text(
                "And this is the secondary text that explains things.")
        dialog.run()
        print("ERROR dialog closed")

        dialog.destroy()

    def on_warn_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.WARNING,
                                   Gtk.ButtonsType.OK_CANCEL, "This is an WARNING MessageDialog")
        dialog.format_secondary_text(
                "And this is the secondary text that explains things.")
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("WARN dialog closed by clicking OK button")
        elif response == Gtk.ResponseType.CANCEL:
            print("WARN dialog closed by clicking CANCEL button")

        dialog.destroy()

    def on_question_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION,
                                   Gtk.ButtonsType.YES_NO, "This is an QUESTION MessageDialog")
        dialog.format_secondary_text(
                "And this is the secondary text that explains things.")
        response = dialog.run()
        if response == Gtk.ResponseType.YES:
            print("QUESTION dialog closed by clicking YES button")
        elif response == Gtk.ResponseType.NO:
            print("QUESTION dialog closed by clicking NO button")

        dialog.destroy()


def main():
    win = MessageDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.ColorChooserDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew (title, parent)

Properties

NameTypeFlagsShort Description
show-editorboolr/wShow editor

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 046
TITLE = "ColorChooserDialog"
DESCRIPTION = """
The Gtk.ColorChooserDialog widget is a dialog for choosing a color.
It implements the Gtk.ColorChooser interface.
"""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango


class ColorChooserDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="ColorChooserDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        self.textview = Gtk.TextView()
        self.textview.set_editable(False)
        self.buffer = self.textview.get_buffer()
        self.buffer.set_text("The only victory over love is flight.", -1)
        button = Gtk.Button("Select Color")
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 50, 30)
        fix.put(self.textview, 30, 90)
        self.add(fix)
        self.show_all()

    def on_clicked(self, widget):
        cdia = Gtk.ColorChooserDialog()
        response = cdia.run()

        if response == Gtk.ResponseType.OK:
            rgba = cdia.get_rgba()
            # 改变背景颜色
            # self.textview.modify_bg(Gtk.StateType.NORMAL, rgba.to_color())
            # 改变文字颜色
            self.textview.override_color(Gtk.StateFlags.NORMAL, rgba)

        cdia.destroy()


def main():
    win = ColorChooserDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.ColorSelectionDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew (title)
get_color_selection ()

Properties

NameTypeFlagsShort Description
cancel-buttonGtk.WidgetrThe cancel button of the dialog.
color-selectionGtk.WidgetrThe color selection embedded in the dialog.
help-buttonGtk.WidgetrThe help button of the dialog.
ok-buttonGtk.WidgetrThe OK button of the dialog.

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 047
TITLE = "ColorSelectionDialog"
DESCRIPTION = ""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango


class ColorSelectionDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="ColorSelectionDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        self.textview = Gtk.TextView()
        self.textview.set_editable(False)
        self.buffer = self.textview.get_buffer()
        self.buffer.set_text("The only victory over love is flight.", -1)
        button = Gtk.Button("Select Color")
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 50, 30)
        fix.put(self.textview, 30, 90)
        self.add(fix)
        self.show_all()

    def on_clicked(self, widget):
        cdia = Gtk.ColorSelectionDialog()
        response = cdia.run()

        if response == Gtk.ResponseType.OK:
            # widget Gtk.ColorSelection
            colorselection = cdia.get_color_selection()
            rgba = colorselection.get_current_rgba()
            # 改变背景颜色
            # self.textview.modify_bg(Gtk.StateType.NORMAL, rgba.to_color())
            # 改变文字颜色
            self.textview.override_color(Gtk.StateFlags.NORMAL, rgba)

        cdia.destroy()


def main(demoapp=None):
    win = ColorSelectionDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.FontChooserDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew (title, parent)

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 048
TITLE = "FontChooseDialog"
DESCRIPTION = """
The Gtk.FontChooserDialog widget is a dialog for selecting a font.
It implements the Gtk.FontChooser interface.
"""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango


class FontChooserDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="FontChooserDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        self.label = Gtk.Label("The only victory over love is flight.")
        button = Gtk.Button("Select font")
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 50, 30)
        fix.put(self.label, 30, 90)
        self.add(fix)
        self.show_all()

    def on_clicked(self, widget):
        fdia = Gtk.FontChooserDialog("Select font name")
        response = fdia.run()

        if response == Gtk.ResponseType.OK:
            font_desc = fdia.get_font_desc()
            if font_desc:
                self.label.modify_font(font_desc)

        fdia.destroy()


def main():
    win = FontChooserDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.FontSelectionDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew (title)
get_cancel_button ()
get_font_name ()
get_font_selection ()
get_ok_button ()
get_preview_text ()
set_font_name (fontname)
set_preview_text (text)

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 049
TITLE = "FontSelectionDialog"
DESCRIPTION = ""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango


class FontChooseDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="FontSelectionDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        self.label = Gtk.Label("The only victory over love is flight.")
        button = Gtk.Button("Select font")
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 50, 30)
        fix.put(self.label, 30, 90)
        self.add(fix)
        self.show_all()

    def on_clicked(self, widget):
        fdia = Gtk.FontSelectionDialog("Select font name")
        response = fdia.run()

        if response == Gtk.ResponseType.OK:
            font_desc = Pango.FontDescription(fdia.get_font_name())
            if font_desc:
                self.label.modify_font(font_desc)

        fdia.destroy()


def main():
    win = FontChooseDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.AboutDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
add_credit_section (section_name, people)
get_artists ()
get_authors ()
get_comments ()
get_copyright ()
get_documenters ()
get_license ()
get_license_type ()
get_logo ()
get_logo_icon_name ()
get_program_name ()
get_translator_credits ()
get_version ()
get_website ()
get_website_label ()
get_wrap_license ()
set_artists (artists)
set_authors (authors)
set_comments (comments)
set_copyright (copyright)
set_documenters (documenters)
set_license (license)
set_license_type (license_type)
set_logo (logo)
set_logo_icon_name (icon_name)
set_program_name (name)
set_translator_credits (translator_credits)
set_version (version)
set_website (website)
set_website_label (website_label)
set_wrap_license (wrap_license)

Virtual Methods

do_activate_link (uri)

Properties

NameTypeFlagsShort Description
artists[str]r/w/enList of people who have contributed artwork to the program
authors[str]r/w/enList of authors of the program
commentsstrr/w/enComments about the program
copyrightstrr/w/enCopyright information for the program
documenters[str]r/w/enList of people documenting the program
licensestrr/w/enThe license of the program
license-typeGtk.Licenser/w/enThe license type of the program
logoGdkPixbuf.Pixbufr/w/enA logo for the about box. If this is not set, it defaults to Gtk.Window.get_default_icon_list()
logo-icon-namestrr/w/enA named icon to use as the logo for the about box.
program-namestrr/w/enThe name of the program. If this is not set, it defaults to GLib.get_application_name()
translator-creditsstrr/w/enCredits to the translators. This string should be marked as translatable
versionstrr/w/enThe version of the program
websitestrr/w/enThe URL for the link to the website of the program
website-labelstrr/w/enThe label for the link to the website of the program
wrap-licenseboolr/w/enWhether to wrap the license text.

Signals

NameShort Description
activate-linkThe signal which gets emitted to activate a URI.

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 050
TITLE = "AboutDialog"
DESCRIPTION = """
The Gtk.AboutDialog offers a simple way to display information about a program like its
logo, name, copyright, website and license. It is also possible to give credits to the authors,
documenters, translators and artists who have worked on the program.
An about dialog is typically opened when the user selects the About option from the Help menu.
All parts of the dialog are optional.
"""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
import webbrowser


class AboutDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="AboutDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        button = Gtk.Button("About")
        button.set_size_request(80, 30)
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 20, 20)

        self.add(fix)
        self.show_all()

    def on_clicked(self, widget):
        about = Gtk.AboutDialog()
        about.set_program_name("Battery")
        about.set_version("0.1")
        about.set_copyright("(c) Jan Bodnar")
        about.set_comments("Battery is a simple tool for battery checking")
        about.set_website("http://www.yuxiaosan.tk")
        about.set_logo(Gtk.IconTheme.get_default().load_icon("battery", 48, 0))
        about.add_credit_section("Credit", ["yuxiaosan", "Tom"])
        about.connect("activate-link", self.click_link)
        about.run()
        about.destroy()

    @staticmethod
    def click_link(widget, url):
        webbrowser.open(url)
        return True


def main():
    win = AboutDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.AppChooserDialog

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew (parent, flags, file)
staticnew_for_content_type (parent, flags, content_type)
get_heading ()
get_widget ()
set_heading (heading)

Properties

NameTypeFlagsShort Description
gfileGio.Filer/w/coThe Gio.File used by the app chooser dialog
headingstrr/wThe text to show at the top of the dialog

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 051
TITLE = "AppChooserDialog"
DESCRIPTION = """
Gtk.AppChooserDialog shows a Gtk.AppChooserWidget inside a Gtk.Dialog.
"""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Gio


class AppChooserDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="AppChooserDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        button = Gtk.Button("Select APP")
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 50, 30)
        self.add(fix)
        self.show_all()

    @staticmethod
    def on_clicked(widget):
        dialog = Gtk.AppChooserDialog(gfile=Gio.File.new_for_path("../../../Data/apple.png"))
        response = dialog.run()
        dialog.destroy()


def main():
    win = AppChooserDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.FileChooserDialog

继承关系

这里写图片描述

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/16
# section 052
TITLE = "FileChooserDialog"
DESCRIPTION = """
Gtk.FileChooserDialog is a dialog box suitable for use with “File/Open” or “File/Save as” commands.
This widget works by putting a Gtk.FileChooserWidget inside a Gtk.Dialog
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class FileChooserWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="FileChooserDialog Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Choose File")
        button1.connect("clicked", self.on_file_clicked)
        box.add(button1)

        button2 = Gtk.Button("Choose Folder")
        button2.connect("clicked", self.on_folder_clicked)
        box.add(button2)

    def on_file_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
                                       Gtk.FileChooserAction.OPEN,
                                       (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                        Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        self.add_filters(dialog)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()

    @staticmethod
    def add_filters(dialog):
        filter_text = Gtk.FileFilter()
        filter_text.set_name("Text files")
        filter_text.add_mime_type("text/plain")
        dialog.add_filter(filter_text)

        filter_py = Gtk.FileFilter()
        filter_py.set_name("Python files")
        filter_py.add_mime_type("text/x-python")
        dialog.add_filter(filter_py)

        filter_any = Gtk.FileFilter()
        filter_any.set_name("Any files")
        filter_any.add_pattern("*")
        dialog.add_filter(filter_any)

    def on_folder_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a folder", self,
                                       Gtk.FileChooserAction.SELECT_FOLDER,
                                       (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                        "Select", Gtk.ResponseType.OK))
        dialog.set_default_size(800, 400)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Select clicked")
            print("Folder selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()


def main():
    win = FileChooserWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

Gtk.RecentChooserDialog

继承关系

这里写图片描述

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/27
# section 053
TITLE = "RecentChooseDialog"
DESCRIPTION = """
Gtk.RecentChooserDialog is a dialog box suitable for displaying the recently used documents.
This widgets works by putting a Gtk.RecentChooserWidget inside a Gtk.Dialog.
It exposes the Gtk.RecentChooserIface interface, so you can use all the Gtk.RecentChooser
functions on the recent chooser dialog as well as those for Gtk.Dialog.
"""

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango
import os
import urllib.parse


class RecentChooserDialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="RecentChooserDialog Demo")
        self.set_border_width(10)
        self.set_default_size(200, 100)
        button = Gtk.Button("RecentChoose")
        button.connect("clicked", self.on_clicked)

        fix = Gtk.Fixed()
        fix.put(button, 50, 30)
        self.add(fix)
        self.show_all()

    def on_clicked(self, widget):
        dialog = Gtk.RecentChooserDialog(title="Recent Documents", parent=self, manager=None,
                                         buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                                  Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
        response = dialog.run()

        if response == Gtk.ResponseType.ACCEPT:
            info = dialog.get_current_item()
            uri = urllib.parse.urlsplit(info.get_uri(), "file").path
            # utf-8
            uri = urllib.parse.unquote(uri)
            print(uri)
            if os.path.exists(uri):
                if os.path.isfile(uri):
                    print(open(uri, encoding="utf-8").readlines())
                else:
                    print("it's a dir")
            else:
                print("file not exists")

        dialog.destroy()


def main():
    win = RecentChooserDialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

自定义Dialog

例子

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/16
# section 054
TITLE = "CustomDialog"
DESCRIPTION = ""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class DialogExample(Gtk.Dialog):
    def __init__(self, parent):
        Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
                            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                             Gtk.STOCK_OK, Gtk.ResponseType.OK))

        self.set_default_size(150, 100)

        label = Gtk.Label("This is a dialog to display additional information")

        box = self.get_content_area()
        box.add(label)
        box.add(Gtk.Button("button"))
        box.add(Gtk.Entry())
        self.show_all()


class DialogWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Dialog Example")

        self.set_border_width(6)

        button = Gtk.Button("Open dialog")
        button.connect("clicked", self.on_button_clicked)

        self.add(button)

    def on_button_clicked(self, widget):
        dialog = DialogExample(self)
        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            print("The OK button was clicked")
        elif response == Gtk.ResponseType.CANCEL:
            print("The Cancel button was clicked")

        dialog.destroy()


def main():
    win = DialogWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()





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

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Dialog 中切换布局可以使用 Dialog 的 setContentView() 方法。该方法可以在运行时动态地改变 Dialog布局。 下面是一个示例代码: ``` // 创建 Dialog Dialog dialog = new Dialog(context); // 设置 Dialog 的初始布局 dialog.setContentView(R.layout.layout1); // 获取 Dialog 的根布局 View rootView = dialog.getWindow().getDecorView().findViewById(android.R.id.content); // 找到布局1中的按钮 Button button1 = rootView.findViewById(R.id.button1); // 设置按钮的点击事件 button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 切换到布局2 dialog.setContentView(R.layout.layout2); } }); // 找到布局2中的按钮 Button button2 = rootView.findViewById(R.id.button2); // 设置按钮的点击事件 button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 切换到布局1 dialog.setContentView(R.layout.layout1); } }); // 显示 Dialog dialog.show(); ``` 在上面的代码中,我们首先创建了一个 Dialog,并设置了初始的布局为 layout1。然后获取了 Dialog 的根布局 rootView,然后找到了布局1中的按钮 button1,并设置了该按钮的点击事件,当点击该按钮时,我们将 Dialog布局切换成 layout2。同样地,我们也找到了布局2中的按钮 button2,并设置了该按钮的点击事件,当点击该按钮时,我们将 Dialog布局切换成 layout1。 注意,为了获取 Dialog 的根布局,我们使用了 getWindow().getDecorView().findViewById(android.R.id.content) 方法,这是因为 Dialog 中的布局不一定是直接添加到 Dialog 中的,可能会被嵌套在一些其他的 View 中,因此需要通过该方法来获取 Dialog 的根布局
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sanxiaochengyu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值