Android官方入门文档[17]构建灵活的UI

简介: Android官方入门文档[17]构建灵活的UIBuilding a Flexible UI构建灵活的UI This lesson teaches you to1.

Android官方入门文档[17]构建灵活的UI


Building a Flexible UI
构建灵活的UI

 

This lesson teaches you to
1.Add a Fragment to an Activity at Runtime
2.Replace One Fragment with Another

You should also read
•Fragments
•Supporting Tablets and Handsets
这节课教你
1.在运行时新增一个片段给一个活动
2.用另一片段替换一个片段

你也应该阅读
•片段
•支持平板电脑和手持设备

Try it out
试试吧

Download the sample
FragmentBasics.zip
下载样本
FragmentBasics.zip

When designing your application to support a wide range of screen sizes, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space.
当设计你的应用程序支持多种屏幕尺寸,您可以重用片段在不同的布局结构优化的基础上可用的屏幕空间的用户体验。

For example, on a handset device it might be appropriate to display just one fragment at a time for a single-pane user interface. Conversely, you may want to set fragments side-by-side on a tablet which has a wider screen size to display more information to the user.
例如,一个手持设备上也可能是适当的时间为一个单窗格的用户界面,来显示只有一个片段。反之,你可能要设置片段并排侧片有更宽的屏幕尺寸可显示更多的信息给用户。
 
Figure 1. Two fragments, displayed in different configurations for the same activity on different screen sizes. On a large screen, both fragments fit side by side, but on a handset device, only one fragment fits at a time so the fragments must replace each other as the user navigates.
图1的两个片段,用于在不同的屏幕尺寸相同的活性显示在不同的配置。在大屏幕上,这两个片段拟合并排,但一个手持设备上,只有一个片段装配在一个时间,以便用户导航片段必须相互取代。

The FragmentManager class provides methods that allow you to add, remove, and replace fragments to an activity at runtime in order to create a dynamic experience.
该FragmentManager类提供了一些方法,使您可以添加,删除和替换片段活动在运行时,以创造一个动态的体验。

 

Add a Fragment to an Activity at Runtime
在运行时新增一个片段给一个活动


--------------------------------------------------------------------------------

Rather than defining the fragments for an activity in the layout file—as shown in the previous lesson with the <fragment> element—you can add a fragment to the activity during the activity runtime. This is necessary if you plan to change fragments during the life of the activity.
而不是限定的片段为活动在布局文件中上一课与<片段>示元件可以活动运行期间添加到片段的活性。如果你计划活动的生命周期内改变片段,这是必要的。

To perform a transaction such as add or remove a fragment, you must use the FragmentManager to create a FragmentTransaction, which provides APIs to add, remove, replace, and perform other fragment transactions.
为了进行交易,如添加或删除片段,则必须使用FragmentManager创建FragmentTransaction,它提供的API来添加,删除,替换,以及执行其他片段交易。

If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity's onCreate() method.
如果你的活动可以使片段被删除,取而代之,你应该活动的OnCreate()方法中添加初始片段活动。

An important rule when dealing with fragments—especially when adding fragments at runtime—is that your activity layout must include a container View in which you can insert the fragment.
一个重要的规则时的片段,尤其是在加时的片段与处理运行时,是你的活动布局必须有一个容器视图,可以在其中插入片段。

The following layout is an alternative to the layout shown in the previous lesson that shows only one fragment at a time. In order to replace one fragment with another, the activity's layout includes an empty FrameLayout that acts as the fragment container.
下面的布局是一种替代上一课中所示的布局只显示一次一个片段。为了取代一个片段与另一种,活动的布局包括一个空的FrameLayout充当片段容器。

Notice that the filename is the same as the layout file in the previous lesson, but the layout directory does not have the large qualifier, so this layout is used when the device screen is smaller than large because the screen does not fit both fragments at the same time.
请注意,文件名是一样的,在上一课布局文件,但布局目录没有大的限定符,所以这种布局时使用的设备的屏幕比large小,因为屏幕在同一时间不适合两个片段。

res/layout/news_articles.xml:
<FrameLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Inside your activity, call getSupportFragmentManager() to get a FragmentManager using the Support Library APIs. Then call beginTransaction() to create a FragmentTransaction and call add() to add a fragment.
在你的活动,调用getSupportFragmentManager()来获得使用支持库API的FragmentManager。然后调用的BeginTransaction()来创建一个FragmentTransaction并调用增加()来添加一个片段。

You can perform multiple fragment transaction for the activity using the same FragmentTransaction. When you're ready to make the changes, you must call commit().
可以使用相同的FragmentTransaction活性执行多个片段事务。当你准备好了做出改变,你必须调用commit()。

For example, here's how to add a fragment to the previous layout:
例如,这里是如何片段添加到以前的布局:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            HeadlinesFragment firstFragment = new HeadlinesFragment();
            
            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());
            
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }
}


 

 

Because the fragment has been added to the FrameLayout container at runtime—instead of defining it in the activity's layout with a <fragment> element—the activity can remove the fragment and replace it with a different one.
因为该片段已被添加了<fragment>元素的活性定义它在活动的布局可以删除片段,并将其与不同的一个replace到的FrameLayout容器在运行时,代替。

 

Replace One Fragment with Another
用另一片段替换一个片段


--------------------------------------------------------------------------------

The procedure to replace a fragment is similar to adding one, but requires the replace() method instead of add().
步骤替换的片段是类似于添加一种,但需要replace()方法,而不是add()。

Keep in mind that when you perform fragment transactions, such as replace or remove one, it's often appropriate to allow the user to navigate backward and "undo" the change. To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit the FragmentTransaction.
请记住,当你执行片段交易,如替换或删除一个,它往往是适当的,允许用户浏览后退,“撤销”的转变。为了使用户能够通过碎片交易向后导航,你必须调用addToBackStack(),您提交FragmentTransaction之前。

Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced.
注意:当您删除或替换片段和交易添加到后面的堆栈,即去掉停止片段(不被破坏)。如果用户导航回恢复片段,将重新启动。如果不事务添加到后面栈,然后取出或替换时,该片段被破坏。

Example of replacing one fragment with another:
用另一个替换一个片段的例子:

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();


 

 

The addToBackStack() method takes an optional string parameter that specifies a unique name for the transaction. The name isn't needed unless you plan to perform advanced fragment operations using the FragmentManager.BackStackEntry APIs.
该addToBackStack()方法接受一个可选的字符串参数,指定一个唯一的名称进行交易。除非你打算执行使用FragmentManager.BackStackEntry API的先进片段操作的名称是不需要的。

Next: Communicating with Other Fragments
下一页:通信与其它片段

本文翻译自:https://developer.android.com/training/basics/fragments/fragment-ui.html

目录
相关文章
|
2月前
|
存储 消息中间件 人工智能
【04】AI辅助编程完整的安卓二次商业实战-寻找修改替换新UI首页图标-菜单图标-消息列表图标-优雅草伊凡
【04】AI辅助编程完整的安卓二次商业实战-寻找修改替换新UI首页图标-菜单图标-消息列表图标-优雅草伊凡
126 4
|
搜索推荐 Android开发 开发者
探索安卓开发中的自定义视图:打造个性化UI组件
【10月更文挑战第39天】在安卓开发的世界中,自定义视图是实现独特界面设计的关键。本文将引导你理解自定义视图的概念、创建流程,以及如何通过它们增强应用的用户体验。我们将从基础出发,逐步深入,最终让你能够自信地设计和实现专属的UI组件。
|
11月前
|
XML 搜索推荐 前端开发
安卓开发中的自定义视图:打造个性化UI组件
在安卓应用开发中,自定义视图是一种强大的工具,它允许开发者创造独一无二的用户界面元素,从而提升应用的外观和用户体验。本文将通过一个简单的自定义视图示例,引导你了解如何在安卓项目中实现自定义组件,并探讨其背后的技术原理。我们将从基础的View类讲起,逐步深入到绘图、事件处理以及性能优化等方面。无论你是初学者还是有经验的开发者,这篇文章都将为你提供有价值的见解和技巧。
|
12月前
|
XML 数据库 Android开发
探索Android开发:从入门到精通的旅程
在这篇文章中,我们将一起踏上一段激动人心的旅程,通过深入浅出的方式,解锁Android开发的秘密。无论你是编程新手还是有经验的开发者,本文都将为你提供宝贵的知识和技能,帮助你构建出色的Android应用。我们将从基础概念开始,逐步深入到高级技巧和最佳实践,最终实现从初学者到专家的转变。让我们开始吧!
272 3
|
XML 前端开发 Android开发
Android:UI:Drawable:View/ImageView与Drawable
通过本文的介绍,我们详细探讨了Android中Drawable、View和ImageView的使用方法及其相互关系。Drawable作为图像和图形的抽象表示,提供了丰富的子类和自定义能力,使得开发者能够灵活地实现各种UI效果。View和ImageView则通过使用Drawable实现了各种图像和图形的显示需求。希望本文能为您在Android开发中使用Drawable提供有价值的参考和指导。
302 2
|
存储 前端开发 测试技术
Android kotlin MVVM 架构简单示例入门
Android kotlin MVVM 架构简单示例入门
257 1
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
299 7
|
Android开发 开发者
安卓开发中的自定义视图:从入门到精通
【9月更文挑战第19天】在安卓开发的广阔天地中,自定义视图是一块充满魔力的土地。它不仅仅是代码的堆砌,更是艺术与科技的完美结合。通过掌握自定义视图,开发者能够打破常规,创造出独一无二的用户界面。本文将带你走进自定义视图的世界,从基础概念到实战应用,一步步展示如何用代码绘出心中的蓝图。无论你是初学者还是有经验的开发者,这篇文章都将为你打开一扇通往创意和效率的大门。让我们一起探索自定义视图的秘密,将你的应用打造成一件艺术品吧!
175 10
|
IDE Java 程序员
安卓应用开发入门:打造你的第一个“Hello World”
【9月更文挑战第11天】在编程的世界里,每一个初学者的旅程都从一个简单的“Hello World”开始。本文将带领安卓开发的新手们,通过简单直观的方式,一步步构建出自己的第一个安卓应用。我们将探索安卓工作室(Android Studio)的安装、项目的创建,以及如何运行和调试你的应用。无论你是编程新手还是想扩展技能的老手,这篇文章都将为你打开一扇通往安卓世界的大门。
425 8
|
XML Android开发 UED
💥Android UI设计新风尚!掌握Material Design精髓,让你的界面颜值爆表!🎨
随着移动应用市场的蓬勃发展,用户对界面设计的要求日益提高。为此,掌握由Google推出的Material Design设计语言成为提升应用颜值和用户体验的关键。本文将带你深入了解Material Design的核心原则,如真实感、统一性和创新性,并通过丰富的组件库及示例代码,助你轻松打造美观且一致的应用界面。无论是色彩搭配还是动画效果,Material Design都能为你的Android应用增添无限魅力。
349 1

热门文章

最新文章

下一篇
oss云网关配置