Fragment-学习笔记(一)

1、Design Philosophy设计理念

Fragment是Android 3.0 (API level 11)引入的新API,Fragment代表Activity的子模块。你可以把Fragment理解为Acticity的模块片段,它有自己的生命周期,可以接受它自己的输入事件,可以在Activity运行时加载或删除。

一个Fragment必须嵌入在Activity中使用,它的生命周期直接受到Activity的生命周期的影响。比如,当activity 处于paused状态时,该activity内的所有fragment也paused,当activity处于运行时(它在生命周期的resumed状态,有时被称为running),你可以独立操作每个fragment,添加或删除它。当你执行一次fragment事务时,你还可以把事务添加进返回栈,返回栈被activity管理。每个activity中的返回栈条目都记录了被触发的fragment事务。返回栈允许倒退事务(向后导航),通过按返回键。

你应该把fragment设计为一个模块的、可重用的组件,这样一个fragment可以被嵌入到多个activity中。所以你应把它设计成可重复使用,并且避免直接从一个碎片中操作另一个碎片.

2、android studio新建平板模拟器
在AS的工具栏有几个常用的按钮,分别是 Gradle同步、AVD Manager、SDK Manager、DDMS ,如下图所示:

  • Gradle同步:在你项目运行或者更改Gradle配置后点击下这个按钮,会下载相应的依赖
  • AVD Manager:模拟器管理
  • SDK Manager:SDK管理
  • DDMS:点击"Android Device Monitor"即可打开DDMS,即 Dalvik Debug Monitor Service,Dalvik调试监控服务。
点击"AVD Manager"、"Create a virtual device",选择

其余默认配置,点击“Finish”,如下启动。
会呈现一个Portrait orientation 的screen,rotate the device screen to Landscape with ctrl+F11,Then can see:

3、简单用法
新建一个左侧布局fragment_left.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button"/>
</LinearLayout>
新建一个右侧布局fragment_right.xml
<?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:background="#00ff00"
              android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:text="This is the right Fragment"/>
</LinearLayout>
接着新建一个LeftFragment、RightFragment,AS会自动生成layout文件和相关代码加载布局。
该类继承自Fragment,可能会有两个不同包下的Fragment,当面向Android4.0以上版本时使用
import android .app.Fragment; 另一个包下的是兼容低版本。重写onCreateView() 方法,通过LayoutInflater的inflate()方法将布局文件动态加载进来。
public class RightFragment extends Fragment {
    public RightFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_right, container, false);
    }
}
RightFragment代码一样,仅加载布局文件名不同。
然后修改activity_main.xml,使用<fragment>标签在布局中添加碎片,android:name属性指定添加的碎片的类名。
<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"
                tools:context=".MainActivity">
    <fragment
        android:id="@+id/fragment_left"
        android:name="com.example.sun.m060113a.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <fragment
        android:id="@+id/fragment_right"
        android:name="com.example.sun.m060113a.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"/>
</LinearLayout>
结果:

4、Building a Flexible UI 动态添加碎片
新建AnotherRightFragment,fragment_another_right。作为另一个右侧碎片,和上面的右侧碎片代码基本相同,只是背景色变成黄色,文字稍改。
<?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:background="#ffff00"
              android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:text="This is anther right Fragment"/>
</LinearLayout>
public class AnotherRightFragment extends Fragment {
    public AnotherRightFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_another_right, container, false);
    }
}
修改activity_main.xml
<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"
                tools:context=".MainActivity">
    <fragment
        android:id="@+id/fragment_left"
        android:name="com.example.sun.m060113a.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <FrameLayout
        android:id="@+id/right_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent "
        android:layout_weight="2">
        <fragment
            android:id="@+id/fragment_right"
            android:name="com.example.sun.m060113a.RightFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </FrameLayout>
</LinearLayout>
方法将右侧碎片放入一个FrameLayout中,它没有任何布局方式,所以控件都放在左上角。之后在代码中替换FrameLayout中的内容,实现动态添加碎片的功能。修改MainActivity的代码如下:
package com.example.sun.m060113a;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button:
                AnotherRightFragment fragment=new AnotherRightFragment();
                FragmentManager fragmentManager=getFragmentManager();
                FragmentTransaction transaction=fragmentManager.beginTransaction();
                transaction.replace(R.id.right_layout,fragment);
                transaction.commit();
                break;
            default:
                break;
        }
    }
}

结果:

5、使用返回栈
上面中按下返回键会退出程序,使用返回栈可以返回到上一个碎片,修改MainActivity中代码:
@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.button:
            AnotherRightFragment fragment=new AnotherRightFragment();
            FragmentManager fragmentManager=getFragmentManager();
            FragmentTransaction transaction=fragmentManager.beginTransaction();
            transaction.replace(R.id.right_layout,fragment);
            transaction.addToBackStack(null);//参数接受一个String名字用于描述返回栈的状态,传入NULL即可。
            transaction.commit();
            break;
        default:
            break;
    }
}
这时可以看到,按下返回键没有退出,而是回到了上一个碎片,再次按下返回键才退出。
 
   










  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值