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

目录
相关文章
|
1天前
|
JavaScript Java Maven
云效产品使用常见问题之android sdk 构建出aar后,上传到私有maven仓库失败如何解决
云效作为一款全面覆盖研发全生命周期管理的云端效能平台,致力于帮助企业实现高效协同、敏捷研发和持续交付。本合集收集整理了用户在使用云效过程中遇到的常见问题,问题涉及项目创建与管理、需求规划与迭代、代码托管与版本控制、自动化测试、持续集成与发布等方面。
|
5天前
|
缓存 移动开发 Android开发
构建高效Android应用:从优化用户体验到提升性能表现
【4月更文挑战第18天】 在移动开发的世界中,打造一个既快速又流畅的Android应用并非易事。本文深入探讨了如何通过一系列创新的技术策略来提升应用性能和用户体验。我们将从用户界面(UI)设计的简约性原则出发,探索响应式布局和Material Design的实践,再深入剖析后台任务处理、内存管理和电池寿命优化的技巧。此外,文中还将讨论最新的Android Jetpack组件如何帮助开发者更高效地构建高质量的应用。此内容不仅适合经验丰富的开发者深化理解,也适合初学者构建起对Android高效开发的基础认识。
2 0
|
5天前
|
移动开发 Android开发 开发者
构建高效Android应用:采用Kotlin进行内存优化的策略
【4月更文挑战第18天】 在移动开发领域,性能优化一直是开发者关注的焦点。特别是对于Android应用而言,由于设备和版本的多样性,确保应用流畅运行且占用资源少是一大挑战。本文将探讨使用Kotlin语言开发Android应用时,如何通过内存优化来提升应用性能。我们将从减少不必要的对象创建、合理使用数据结构、避免内存泄漏等方面入手,提供实用的代码示例和最佳实践,帮助开发者构建更加高效的Android应用。
5 0
|
7天前
|
缓存 移动开发 Java
构建高效的Android应用:内存优化策略
【4月更文挑战第16天】 在移动开发领域,尤其是针对资源有限的Android设备,内存优化是提升应用性能和用户体验的关键因素。本文将深入探讨Android应用的内存管理机制,分析常见的内存泄漏问题,并提出一系列实用的内存优化技巧。通过这些策略的实施,开发者可以显著减少应用的内存占用,避免不必要的后台服务,以及提高垃圾回收效率,从而延长设备的电池寿命并确保应用的流畅运行。
|
11天前
|
存储 数据库 Android开发
构建高效安卓应用:采用Jetpack架构组件优化用户体验
【4月更文挑战第12天】 在当今快速发展的数字时代,Android 应用程序的流畅性与响应速度对用户满意度至关重要。为提高应用性能并降低维护成本,开发者需寻求先进的技术解决方案。本文将探讨如何利用 Android Jetpack 中的架构组件 — 如 LiveData、ViewModel 和 Room — 来构建高质量的安卓应用。通过具体实施案例分析,我们将展示这些组件如何协同工作以实现数据持久化、界面与逻辑分离,以及确保数据的即时更新,从而优化用户体验并提升应用的可维护性和可测试性。
|
13天前
|
XML 移动开发 Android开发
构建高效安卓应用:采用Jetpack Compose实现动态UI
【4月更文挑战第10天】 在现代移动开发中,用户界面的流畅性和响应性对于应用的成功至关重要。随着技术的不断进步,安卓开发者寻求更加高效和简洁的方式来构建动态且吸引人的UI。本文将深入探讨Jetpack Compose这一革新性技术,它通过声明式编程模型简化了UI构建过程,并提升了性能与跨平台开发的可行性。我们将从基本概念出发,逐步解析如何利用Jetpack Compose来创建具有数据动态绑定能力的安卓应用,同时确保应用的高性能和良好用户体验。
15 0
|
14天前
|
XML Java Android开发
Android之UI基础控件
Android之UI基础控件
|
15天前
|
监控 API Android开发
构建高效安卓应用:探究Android 12中的新特性与性能优化
【4月更文挑战第8天】 在本文中,我们将深入探讨Android 12版本引入的几项关键技术及其对安卓应用性能提升的影响。不同于通常的功能介绍,我们专注于实际应用场景下的性能调优实践,以及开发者如何利用这些新特性来提高应用的响应速度和用户体验。文章将通过分析内存管理、应用启动时间、以及新的API等方面,为读者提供具体的技术实现路径和代码示例。
|
15天前
|
移动开发 API Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【4月更文挑战第7天】 在移动开发领域,性能优化和应用响应性的提升一直是开发者追求的目标。近年来,Kotlin语言因其简洁性和功能性在Android社区中受到青睐,特别是其对协程(Coroutines)的支持,为编写异步代码和处理并发任务提供了一种更加优雅的解决方案。本文将探讨Kotlin协程在Android开发中的应用,揭示其在提高应用性能和简化代码结构方面的潜在优势,并展示如何在实际项目中实现和优化协程。
|
15天前
|
XML 开发工具 Android开发
构建高效的安卓应用:使用Jetpack Compose优化UI开发
【4月更文挑战第7天】 随着Android开发不断进化,开发者面临着提高应用性能与简化UI构建流程的双重挑战。本文将探讨如何使用Jetpack Compose这一现代UI工具包来优化安卓应用的开发流程,并提升用户界面的流畅性与一致性。通过介绍Jetpack Compose的核心概念、与传统方法的区别以及实际集成步骤,我们旨在提供一种高效且可靠的解决方案,以帮助开发者构建响应迅速且用户体验优良的安卓应用。

热门文章

最新文章