上面的例子显示了怎样把Fragment作为UI的一部分添加到Activity上,但是,你也能够使用Fragment只提供一个后台行为,而没有额外的UI展现。
要添加一个没有UI的Fragment,需要在Activity中使用add(Fragment,String)(给Fragment提供一个唯一的字符串“tag”,而不是视图ID)方法来添加Fragment。但是,因为这样添加的Fragment没有跟Activity布局中的视图关联,它不接受对onCreateView()方法的调用,
因此你不需要实现这个方法。
不能说提供了字符串“tag”的Fragment就是非UIFragment,因为你也可以给有UI的Fragment提供字符串“tag”,但是如果Fragment没有UI,那么只能使用字符串的方法来标识它。如果你想要从Activity获取这个Fragment,需要使用findFragmentByTag()方法。
FragmentRetainInstance.java演示了一个没有UI的使用Fragment作为后台工作器的Activity。
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
/**
* This example shows how you can use a Fragment to easily propagate state
* (such as threads) across activity instances when an activity needs to be
* restarted due to, for example, a configuration change. This is a lot
* easier than using the raw Activity.onRetainNonConfiguratinInstance() API.
*/
public class FragmentRetainInstance extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// First time init, create the UI.
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(android.R.id.content,
new UiFragment()).commit();
}
}
/**
* This is a fragment showing UI that will be updated from work done
* in the retained fragment.
*/
public static class UiFragment extends Fragment {
RetainedFragment mWorkFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_retain_instance, container, false);
// Watch for button clicks.
Button button = (Button)v.findViewById(R.id.restart);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mWorkFragment.restart();
}
});
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getFragmentManager();
// Check to see if we have retained the worker fragment.
mWorkFragment = (RetainedFragment)fm.findFragmentByTag("work");
// If not retained (or first time running), we need to create it.
if (mWorkFragment == null) {
mWorkFragment = new RetainedFragment();
// Tell it who it is working with.
mWorkFragment.setTargetFragment(this, 0);
fm.beginTransaction().add(mWorkFragment, "work").commit();
}
}
}
/**
* This is the Fragment implementation that will be retained across
* activity instances. It represents some ongoing work, here a thread
* we have that sits around incrementing a progress indicator.
*/
public static class RetainedFragment extends Fragment {
ProgressBar mProgressBar;
int mPosition;
boolean mReady = false;
boolean mQuiting = false;
/**
* This is the thread that will do our work. It sits in a loop running
* the progress up until it has reached the top, then stops and waits.
*/
final Thread mThread = new Thread() {
@Override
public void run() {
// We'll figure the real value out later.
int max = 10000;
// This thread runs almost forever.
while (true) {
// Update our shared state with the UI.
synchronized (this) {
// Our thread is stopped if the UI is not ready
// or it has completed its work.
while (!mReady || mPosition >= max) {
if (mQuiting) {
return;
}
try {
wait();
} catch (InterruptedException e) {
}
}
// Now update the progress. Note it is important that
// we touch the progress bar with the lock held, so it
// doesn't disappear on us.
mPosition++;
max = mProgressBar.getMax();
mProgressBar.setProgress(mPosition);
}
// Normally we would be doing some work, but put a kludge
// here to pretend like we are.
synchronized (this) {
try {
wait(50);
} catch (InterruptedException e) {
}
}
}
}
};
/**
* Fragment initialization. We way we want to be retained and
* start our thread.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Tell the framework to try to keep this fragment around
// during a configuration change.
setRetainInstance(true);
// Start up the worker thread.
mThread.start();
}
/**
* This is called when the Fragment's Activity is ready to go, after
* its content view has been installed; it is called both after
* the initial fragment creation and after the fragment is re-attached
* to a new activity.
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Retrieve the progress bar from the target's view hierarchy.
mProgressBar = (ProgressBar)getTargetFragment().getView().findViewById(
R.id.progress_horizontal);
// We are ready for our thread to go.
synchronized (mThread) {
mReady = true;
mThread.notify();
}
}
/**
* This is called when the fragment is going away. It is NOT called
* when the fragment is being propagated between activity instances.
*/
@Override
public void onDestroy() {
// Make the thread go away.
synchronized (mThread) {
mReady = false;
mQuiting = true;
mThread.notify();
}
super.onDestroy();
}
/**
* This is called right before the fragment is detached from its
* current activity instance.
*/
@Override
public void onDetach() {
// This fragment is being detached from its activity. We need
// to make sure its thread is not going to touch any activity
// state after returning from this function.
synchronized (mThread) {
mProgressBar = null;
mReady = false;
mThread.notify();
}
super.onDetach();
}
/**
* API for our UI to restart the progress thread.
*/
public void restart() {
synchronized (mThread) {
mPosition = 0;
mThread.notify();
}
}
}
}
注:本人转载系个人觉得翻译的很好,值得收藏,且自己回头看着方便。
如有兴趣请访问作者官方博客http://blog.csdn.net/FireOfStar
分享到:
相关推荐
- FragmentTransaction是FragmentManager的一个接口,用于对Fragment进行操作,如添加、替换、移除、隐藏和显示等。 - 使用`beginTransaction()`方法开始一个事务,通过`commit()`来提交这些操作,提交后系统会...
Fragment是一个可嵌入到Activity中的UI片段,它可以有自己的生命周期,接收用户输入,并与Activity进行数据交换。Fragment可以单独管理其视图和逻辑,从而提高了代码的可复用性和模块化。 二、XML中添加Fragment的...
压缩包中的`FragmentAnim`可能包含了一个简单的示例项目,展示了如何实现上述的一些动画效果。`说明.htm`文件可能是对示例的解释和指导,包括如何运行和理解代码。通过学习这个例子,开发者可以更好地理解和实践...
在Android应用开发中,Fragment是UI组件的一种,它允许我们构建可重用的模块化界面。Fragment可以在Activity中动态添加、删除或替换,这在设计适应不同屏幕尺寸和配置的应用时非常有用。当我们想要增强用户体验,使...
"android-android-ui-design-patterns.rar"是一个压缩包,包含了关于Android UI设计模式的重要资料,特别是对于GUI(图形用户界面)设计者来说,这份资源极其有价值。 Android UI设计遵循一套规范和最佳实践,旨在...
在Android应用开发中,`Fragment`是Android UI设计的一个核心组件,它允许开发者在单一的Activity中构建可重用的模块化界面。`Fragment`的概念引入于Android 3.0 (API level 11),目的是为了更好地支持平板电脑等大...
在Android开发中,创建一个类似微信的用户界面框架是一项常见的任务,这通常涉及到使用ViewPager结合Fragment来实现页面的切换,并且可能需要添加下拉刷新功能。在这个教程中,我们将深入探讨如何实现这样的功能。 ...
1. 添加Fragment:使用`FragmentTransaction.add()`方法将一个Fragment添加到Activity中。如果不指定容器ID,那么Fragment会被添加到默认的Container中,通常是R.id.container。 2. 替换Fragment:`...
1. 创建Fragment类:首先,你需要创建一个继承自android.app.Fragment或androidx.fragment.app.Fragment的子类,并实现相应的逻辑和UI布局。 ```java public class MyFragment extends Fragment { // 实现Fragment...
在传统的Fragment使用中,通常需要创建一个Transaction对象,然后将Fragment实例添加到Transaction中,最后提交Transaction。这样的步骤在代码中显得繁琐,尤其是在频繁使用Fragment时。为了解决这个问题,开发者...
定义一个接口,Fragment实现该接口并设置监听器,然后在Activity中调用接口方法来传递数据。 ```java // 在Fragment中定义接口 public interface OnDataChangeListener { void onDataChanged(String newData); ...
- `AndroidFragment.zip`可能包含一个基础的Android Fragment项目,用于学习Fragment的基础用法和实践。 7. **Fragment在不同版本上的兼容性**: - 从Android 3.0(API级别11)开始引入Fragment,但通过Android ...
Fragment是Android应用开发中的一个重要组件,它是在Android 3.0(API级别11)引入的,用于构建可重用的、模块化的用户界面部分。在这个"Fragment实例-Android Studio项目"中,我们可以深入理解Fragment的使用方法...
2. **片段(Fragment)**:Fragment是Android UI设计中的一个可重用组件,可以在多个Activity之间共享,使得在不同屏幕尺寸和配置上构建适应性强的用户界面成为可能。 3. **MVP(Model-View-Presenter)模式**:MVP...
首先,Fragment是在Android 3.0(API级别11)引入的,它的主要用途是增强Activity的功能,特别是在Tab导航设计中,每个Tab对应一个Fragment,使得Activity职责更加明确,同时也提高了代码的复用性。Fragment具有自己...
Fragment是Android SDK中的一个重要组件,它允许开发者在一个活动中展示多个相互独立的UI部分。这个项目是在Android Studio 0.5.1版本下进行的,日期为2014年3月14日,这意味着它基于早期版本的Android Studio,可能...
在Android开发中,Fragment是应用程序界面的一个模块化组件,它可以在Activity中承载用户界面部分,使得开发者能够构建更复杂、可重用的布局。"Android代码-安卓原生Fragment演示"是一个项目,专注于展示如何在...
综上所述,FragmentDemo-10是一个学习和实践Android Fragment与TabHost集成的实例,通过它,开发者可以深入理解如何在Android应用中构建具有多标签界面的交互式用户体验。通过阅读源代码和博客文章,你可以更好地...
这里我把5个包合并为一个大包,注意大包里面没包含android-support-annotations-25.3.1 android-support-v4-25.3.1(由下面的5个小包合并) v4-support-compat-25.3.1 v4-support-core-ui-25.3.1 v4-support-core-...
Android Fragment是Android开发中的一个重要组件,它允许开发者在一个Activity中动态地组合多个片段来构成复杂的UI布局。 首先,我们需要了解Fragment是什么以及它的基本功能。Fragment是Android平台的一部分,它被...