从零开始水安卓——Fragment

实际上应该和Activity放在一起讲

https://blog.csdn.net/nishigesb123/article/details/88875292


概述

下面是API中的描述:

Fragment 表示 Activity 中的行为或用户界面部分。您可以将多个片段组合在一个 Activity 中来构建多窗格 UI,以及在多个 Activity 中重复使用某个片段。您可以将片段视为 Activity 的模块化组成部分,它具有自己的生命周期,能接收自己的输入事件,并且您可以在 Activity 运行时添加或移除片段(有点像您可以在不同 Activity 中重复使用的“子 Activity”)。


片段必须始终嵌入在 Activity 中,其生命周期直接受宿主 Activity 生命周期的影响。 例如,当 Activity 暂停时,其中的所有片段也会暂停;当 Activity 被销毁时,所有片段也会被销毁。 不过,当 Activity 正在运行(处于已恢复生命周期状态)时,您可以独立操纵每个片段,如添加或移除它们。 当您执行此类片段事务时,您也可以将其添加到由 Activity 管理的返回栈 — Activity 中的每个返回栈条目都是一条已发生片段事务的记录。 返回栈让用户可以通过按返回按钮撤消片段事务(后退)。


当您将片段作为 Activity 布局的一部分添加时,它存在于 Activity 视图层次结构的某个 ViewGroup内部,并且片段会定义其自己的视图布局。您可以通过在 Activity 的布局文件中声明片段,将其作为<fragment> 元素插入您的 Activity 布局中,或者通过将其添加到某个现有 ViewGroup,利用应用代码进行插入。不过,片段并非必须成为 Activity 布局的一部分;您还可以将没有自己 UI 的片段用作 Activity 的不可见工作线程。


本文描述如何在开发您的应用时使用片段,包括将片段添加到 Activity 返回栈时如何保持其状态、如何与 Activity 及 Activity 中的其他片段共享事件、如何为 Activity 的操作栏发挥作用等等。

  •  Fragment是Activity中用户界面的一个行为或者是一部分。
  • 你可以在一个单独的Activity上把多个Fragment组合成为一个多区域的UI,并且可以在多个Activity中再使用。
  • 你可以认为Fragment是Activity的一个模块零件,它有自己的生命周期,接收它自己的输入事件,并且可以在Activity运行时添加或者删除。
  • Fragment的生命周期直接受其宿主Activity的生命周期的影响。例如,一旦Activity被暂停,它里面的所有Fragment也被暂停,一旦Activity被销毁,它里面的所有Fragment也被销毁。

设计原理

下面部分依旧来源于API:

Android 在 Android 3.0(API 级别 11)中引入了片段,主要是为了给大屏幕(如平板电脑)上更加动态和灵活的 UI 设计提供支持。由于平板电脑的屏幕比手机屏幕大得多,因此可用于组合和交换 UI 组件的空间更大。利用片段实现此类设计时,您无需管理对视图层次结构的复杂更改。 通过将 Activity 布局分成片段,您可以在运行时修改 Activity 的外观,并在由 Activity 管理的返回栈中保留这些更改。

例如,新闻应用可以使用一个片段在左侧显示文章列表,使用另一个片段在右侧显示文章 — 两个片段并排显示在一个 Activity 中,每个片段都具有自己的一套生命周期回调方法,并各自处理自己的用户输入事件。 因此,用户不需要使用一个 Activity 来选择文章,然后使用另一个 Activity 来阅读文章,而是可以在同一个 Activity 内选择文章并进行阅读,如图 1 中的平板电脑布局所示。

您应该将每个片段都设计为可重复使用的模块化 Activity 组件。也就是说,由于每个片段都会通过各自的生命周期回调来定义其自己的布局和行为,您可以将一个片段加入多个 Activity,因此,您应该采用可复用式设计,避免直接从某个片段直接操纵另一个片段。 这特别重要,因为模块化片段让您可以通过更改片段的组合方式来适应不同的屏幕尺寸。 在设计可同时支持平板电脑和手机的应用时,您可以在不同的布局配置中重复使用您的片段,以根据可用的屏幕空间优化用户体验。 例如,在手机上,如果不能在同一 Activity 内储存多个片段,可能必须利用单独片段来实现单窗格 UI。

图 1. 有关由片段定义的两个 UI 模块如何适应不同设计的示例:通过组合成一个 Activity 来适应平板电脑设计,通过单独片段来适应手机设计。

例如 — 仍然以新闻应用为例 — 在平板电脑尺寸的设备上运行时,该应用可以在 Activity A 中嵌入两个片段。 不过,在手机尺寸的屏幕上,没有足以储存两个片段的空间,因此Activity A 只包括用于显示文章列表的片段,当用户选择文章时,它会启动Activity B,其中包括用于阅读文章的第二个片段。 因此,应用可通过重复使用不同组合的片段来同时支持平板电脑和手机,如图 1 所示。

  •  有了fragment,你可以不必去管理视图体系的复杂变化。
  • 通过将activity的布局分割成若干个fragment,可以在运行时编辑activity的呈现,并且那些变化会被保存在由activity管理的后台栈里面。

简而言之——Fragment就是一个安卓设备屏幕尺寸多样化的解决方案。

 理解上并没有太大的困难,所以我们的重点还是放在如何实现。

实现

创建

  • 要创建一个Fragment,必须创建一个Fragment的子类(或是继承自它的子类)。
  • Fragment类的代码看起来很像Activity。它与Activity一样都有回调函数,例如:onCreate()、onStarr()、onPause()、onStop()。事实上,如果你正在将一个现成的Android应用转而使用Fragment来实现,可以简单将代码从Activity的回调函数移植到各自的Fragment回调函数中。
  • 除了基类Fragment,这里还有几个可能会继承的子类:DialogFragment、ListFragment、PerferenceFragment

以下内容来自API文档

通常,您至少应实现以下生命周期方法:

onCreate()

系统会在创建片段时调用此方法。您应该在实现内初始化您想在片段暂停或停止后恢复时保留的必需片段组件。

onCreateView()

系统会在片段首次绘制其用户界面时调用此方法。 要想为您的片段绘制 UI,您从此方法中返回的 View 必须是片段布局的根视图。如果片段未提供 UI,您可以返回 null。

onPause()

系统将此方法作为用户离开片段的第一个信号(但并不总是意味着此片段会被销毁)进行调用。 您通常应该在此方法内确认在当前用户会话结束后仍然有效的任何更改(因为用户可能不会返回)。

大多数应用都应该至少为每个片段实现这三个方法,但您还应该使用几种其他回调方法来处理片段生命周期的各个阶段。 处理片段生命周期部分对所有生命周期回调方法做了更详尽的阐述。

您可能还想扩展几个子类,而不是 Fragment基类:

DialogFragment

显示浮动对话框。使用此类创建对话框可有效地替代使用 Activity 类中的对话框帮助程序方法,因为您可以将片段对话框纳入由 Activity 管理的片段返回栈,从而使用户能够返回清除的片段。

ListFragment

显示由适配器(如 SimpleCursorAdapter)管理的一系列项目,类似于 ListActivity。它提供了几种管理列表视图的方法,如用于处理点击事件的 onListItemClick() 回调。

PreferenceFragment

以列表形式显示 Preference 对象的层次结构,类似于 PreferenceActivity。这在为您的应用创建“设置” Activity 时很有用处。

添加用户界面

Fragment常被作为Activity用户界面的一部分,并且将本身的布局构建到Activity中去。

将Fragment添加到Activity有两种方式:

  1. 在Activity 布局文件里声明Fragment
  2. 通过编码将Fragment添加到已存在的ViewGroup中

如果想在3.0之前的版本使用Fragment,可以使用v4包

准备一个TitleFragment.java并继承Fragment(用于绑定布局中fragment的name属性,下同)

准备一个ContentFragment.java并继承Fragment

方便测试我们把布局改成LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/title_fragment"
        android:name="com.example.a4_7fragment.TitleFragment"
        android:layout_weight="1"
        ></fragment>

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:id="@+id/content_fragment"
        android:name="com.example.a4_7fragment.ContentFragment"
        ></fragment>
</LinearLayout>

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

我们可以把准备的TitleFragment.java和ContentFragment.java看作Activity,所以我们也需要为他们创建对应的布局文件

如title_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#4757AC">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第一个按钮" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第二个按钮" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第三个按钮" />

</LinearLayout>

创建完毕需要在TitleFragment.java进行绑定(重写onCreateView)

package com.example.a4_7fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TitleFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.title_layout,container,false);
        return view;
    }
}

同理,Content也需要配置布局文件和重写onCreateView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#56E75C">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="55sp"
        android:gravity="center"
        android:text="No data"/>
</LinearLayout>
package com.example.a4_7fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ContentFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.content_layout,container,false);
        return view;
    }
}

效果如下:


以上便是第一种方法,下面介绍

如何通过编码将Fragment添加到已存在的ViewGroup中

对MainActivity

 

新建一个Activity,修改其布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity">

    <fragment
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:id="@+id/title_fragment"
        android:name="com.example.a4_7fragment.TitleFragment"
        android:layout_weight="1"
        />
    <FrameLayout
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:id="@+id/content_fragment"
        android:layout_weight="3">
    </FrameLayout>
</LinearLayout>

修改其代码

package com.example.a4_7fragment;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Main2Activity extends AppCompatActivity {

    ContentFragment contentFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        addContentLayout();
    }

    //通过代码添加Fragment
    private void addContentLayout(){
        FragmentManager fm = getFragmentManager();
        //开启一个事务
        FragmentTransaction ft = fm.beginTransaction();
        contentFragment=new ContentFragment();
        //添加Fragment(参数为id)
        ft.add(R.id.content_fragment,contentFragment);
        //ft.remove();删除
        //ft.replace();替换
        //提交事务
        ft.commit();
    }

}

效果不变:

管理

想要管理activity中的fragment,可以使用FragmentManager。可以通过在activity中调用getFragmentManager()获得。
使用FragmentManager可以做如下事情,包括:

  1. 使用findFragmentById()或findFragmentByTag()获取activity中存在的fragment,前者适用于有界面的...后者皆可
  2. 使用popBackStack()(模仿用户的BACK命令)从后台栈弹出fragment
  3. 使用addOnBackStackChangedListener()注册一个监听后台栈变化的监听器

新建Activity(PopBackTaskActivity)

package com.example.a4_7fragment;

import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public class PopBackTaskActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pop_back_task);
    }
    public void oneClick(View v){
        PopBackFragment p1= new PopBackFragment("one");
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.content,p1);
        //把当前fragment添加到Activity栈
        ft.addToBackStack(null);
        ft.commit();
    }
    public void twoClick(View v){
        PopBackFragment p2 = new PopBackFragment("two");
        FragmentTransaction ft=getFragmentManager().beginTransaction();
        ft.replace(R.id.content,p2);
        //把当前fragment添加到Activity栈
        ft.addToBackStack(null);
        ft.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode== KeyEvent.KEYCODE_BACK){
                //判断返回栈里是否有返回值
            if (getFragmentManager().getBackStackEntryCount()==0){
                finish();
            }else {
                //出栈
                getFragmentManager().popBackStack();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

修改其布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PopBackTaskActivity">

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="one"
        android:onClick="oneClick"
        android:textSize="33sp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true">
    </Button>

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="two"
        android:onClick="twoClick"
        android:textSize="33sp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true">
    </Button>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/button4">
    </FrameLayout>

</RelativeLayout>

新建一个Fragment (会自动生成布局文件)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PopBackFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:id="@+id/textView_text"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="66sp"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>
package com.example.a4_7fragment;


import android.app.Fragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * A simple {@link Fragment} subclass.
 */
public class PopBackFragment extends Fragment {

    private String title;

    public PopBackFragment() {
        // Required empty public constructor
    }
    public PopBackFragment(String title){
        this.title = title;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_pop_back,container,false);
        TextView tv=view.findViewById(R.id.textView_text);
        tv.setText(title);
        return view;
    }

}

效果如下: 

参数传递

上方法虽然已经涉及参数传递,然而?面方法传递参数并不安全,结果就是在旋转屏幕的时候,传递的参数会丢失。

(在https://blog.csdn.net/nishigesb123/article/details/88934750一文中提到)

修改PopBackFragment.java文件,我们获取实例传递参数。

package com.example.a4_7fragment;


import android.app.Fragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * A simple {@link Fragment} subclass.
 */
public class PopBackFragment extends Fragment {

    private String title;

    public PopBackFragment() {
        // Required empty public constructor
    }
/*
    public PopBackFragment(String title){
        this.title = title;
    }
*/

    public static PopBackFragment getInstance(String title){
        PopBackFragment p=new PopBackFragment();
        Bundle b=new Bundle();
        b.putString("title",title);
        p.setArguments(b);
        return p;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_pop_back,container,false);
        TextView tv=view.findViewById(R.id.textView_text);
        tv.setText(getArguments().getString("title"));
        return view;
    }

}

 同样的,PopBackTaskActivity也需要进行一定的修改,改动比较小

只需要将对应的点击事件里的原本的new PopBackFragment改为getInstance即可。

//PopBackFragment p1= new PopBackFragment("one");
PopBackFragment p1= PopBackFragment.getInstance("one");

//PopBackFragment p2 = new PopBackFragment("two");
PopBackFragment p2= PopBackFragment.getInstance("two");

可以看到,屏幕旋转参数依旧存在。 

处理事务

在activity中使用fragment的一大特点是具有添加、删除、替换,和执行其它动作的能力,以响应用户的互动。

提交给activity的每一系列变化被称为事务,并且可以用FragmentTransaction中的APIs处理。

你也可以将每一个事务保存在由activity管理的后台栈中,并且允许用户导航回退fragment变更(类似于activity的导航回退)。

与Activity的交互

  • fragment可以通过getActivity()函数访问Activity。
  • 并且可以执行类似于查找activity布局中的视图的任务:View listView = getActivityl.findViewByld(R.id.ist);
  • activity能够调用fragment的函数findFragmentByld()或者findFragmentByTag(),从FragmentManager中获取Fragment
ExampleFragment fragment = (ExampleFragment) getFragmentManagerO).findFragmentByd(R id example _fragment);
  • fragment与activity共享事件的一个好方法是在fragment内部定义一个回调接口,并需要宿主activity实现它。
  • 当activity通过接口接收到回调时,可以在必要时与布局中的其它fragment共享信息。

Main3Activity.java及对应布局

package com.example.a4_7fragment;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Main3Activity extends AppCompatActivity implements MenuFragment.MyMenuListener{

    private MenuFragment menuFragment;
    private MainFragment mainFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        menuFragment = (MenuFragment)getFragmentManager().findFragmentById(R.id.menuFragment);
        mainFragment=(MainFragment) getFragmentManager().findFragmentById(R.id.mainFragment);
    }

    @Override
    public void changeValue(String value) {
        mainFragment.changeTextViewValue(value);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main3Activity">

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/menuFragment"
        android:name="com.example.a4_7fragment.MenuFragment"/>

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:id="@+id/mainFragment"
        android:name="com.example.a4_7fragment.MainFragment"/>
</LinearLayout>

 

MainFragment .java及对应布局

package com.example.a4_7fragment;


import android.app.Fragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends Fragment {

    private TextView textView_value;
    public MainFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_main,container,false);
        textView_value=view.findViewById(R.id.value);
        return view;
    }
    public void changeTextViewValue(String value){
        textView_value.setText(value);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/value"
        android:gravity="center"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

MenuFragment.java及对应布局

package com.example.a4_7fragment;


import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 */
public class MenuFragment extends Fragment implements View.OnClickListener{
    private MyMenuListener myMenuListener;

    public MenuFragment() {
        // Required empty public constructor
    }
    //myMenuListener实例化
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        myMenuListener=(MyMenuListener)activity;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_menu, container, false);
        view.findViewById(R.id.NEWS).setOnClickListener(this);
        view.findViewById(R.id.MUSIC).setOnClickListener(this);
        return view;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.NEWS:
                myMenuListener.changeValue("news");
                break;
            case R.id.MUSIC:
                myMenuListener.changeValue("music");
                break;
        }
    }


    //定义一个回调接口
    public static interface MyMenuListener{
        public void changeValue(String value);
    }

}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MenuFragment">

    <Button
        android:text="NEWS"
        android:id="@+id/NEWS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:text="MUSIC"
        android:id="@+id/MUSIC"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

测试效果


PreferenceFragment

有时候,我们的程序需要提供一些选项功能,能让用户去定制化自己的使用风格。例如,允许用户是否自动保存登录信,允许用户设定某个页面的刷新时间等等。我们可以使用PreferenceActivity基 类去显示给用户一个选项设置的界面。在Android3.0或更高的版本上,可以使用PreferenceFragment类 去实现这个功能。

下面将展示如何去创建和使用PreferenceFragment。

  1. 在res文件来下面新建一个xmI文件夹,在xmI文件夹下面新建一个文件: preferences.xml。
  2. 在包路径下面新建一个类: Fragment继承PreferenceFragment。
  3. 从xmI文件加载选项addPreferencesFromResource(R.xml. preferences);
//在本类中获取shared_pref文件
String name = getPreferenceManager().getSharedPreferencesName();
//获取默认的属性配置
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(this); 
boolean checkbox_preference =sp.getBoolean("checkbox_preference","false"); 

数据会被进行保存 data/data/项目/shared_prefs

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

云无心鸟知还

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

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

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

打赏作者

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

抵扣说明:

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

余额充值