Android Fragment 简单实例

Android Fragment 简单实例

大家好,又见面了,我是全栈君。

  Android上的界面展示都是通过Activity实现的。Activity实在是太经常使用了。我相信大家都已经很熟悉了,这里就不再赘述。 可是Activity也有它的局限性,相同的界面在手机上显示可能很好看,在平板上就未必了,由于平板的屏幕很大。手机的界面放在平板上可能会有过分被拉长、控件间距过大等情况。这个时候更好的体验效果是在Activity中嵌入”小Activity”。然后每个”小Activity”又能够拥有自己的布局。这就是Fragment碎片技术。


一、Fragment简单介绍

  Android是在Android 3.0 (API level 11)開始引入Fragment的。能够把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的生命周期,单独处理自己的输入,在Activity执行的时候能够载入或者移除Fragment模块。

能够把Fragment设计成能够在多个Activity中复用的模块。

当开发的应用程序同一时候适用于平板电脑和手机时。能够利用Fragment实现灵活的布局,改善用户体验。

二、Fragment生命周期

  由于Fragment必须嵌入在Acitivity中使用。所以Fragment的生命周期和它所在的Activity是密切相关的。

  假设Activity是暂停状态。当中全部的Fragment都是暂停状态;假设Activity是stopped状态。这个Activity中全部的Fragment都不能被启动。假设Activity被销毁,那么它当中的全部Fragment都会被销毁。可是,当Activity在活动状态。能够独立控制Fragment的状态,比方加上或者移除Fragment。

  当这样进行fragment transaction(转换)的时候,能够把fragment放入Activity的back stack中。这样用户就能够进行返回操作。
  这里写图片描写叙述
  Activity与Fragment生命周期对照图
  这里写图片描写叙述

三、两个简单实例

  1. 简单的Fragment练习,Activity与Fragment通信
    这里写图片描写叙述
    布局文件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" android:orientation="vertical" tools:context=".MainActivity" >

    <FrameLayout  android:layout_weight="1" android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="0dp" >
    </FrameLayout>

    <android.support.v4.app.FragmentTabHost  android:id="@+id/tab" android:layout_width="fill_parent" android:layout_height="wrap_content" />

</LinearLayout>

Java文件

package com.example.fragmenttabhost;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MyFragment extends ListFragment{

    String show1[] = {"1.1","1.2","1.3","1.4"};
    String show2[] = {"2.1","2.2","2.3","2.4"};
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String show[] = null;
        Bundle bundle = getArguments();
        if(bundle == null)
            show = show1;
        else {
            show = show2;
            Toast.makeText(getActivity(), (CharSequence) bundle.get("key"), 1).show();
        }
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, show));
    }
}
package com.example.fragmenttabhost;

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

public class MainActivity extends FragmentActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentTabHost tabHost = (FragmentTabHost) findViewById(R.id.tab);
        tabHost.setup(this, getSupportFragmentManager(), R.id.content);

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab1"), MyFragment.class, null);
        Bundle b = new Bundle();
        b.putString("key", "I am tab2");
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab2",getResources().getDrawable(R.drawable.ic_launcher)), MyFragment.class, b);

    }

}

执行结果
这里写图片描写叙述
这里写图片描写叙述
2. 比較好看的demo,模仿微信主页面
这里写图片描写叙述
碎片布局文件fragment_1,2,3,4,5.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" >

    <ImageView  android:id="@+id/imageview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitCenter" android:src="@drawable/mm1" >
    </ImageView>

</LinearLayout>

tab_item_view.xmlbutton布局

<?

xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <ImageView android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false" android:padding="3dp" android:src="@drawable/tab_home_btn"> </ImageView> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="首页" android:textSize="10sp" android:textColor="#ffffff"> </TextView> </LinearLayout>

主页面布局main_tab_layout.xml

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

    <FrameLayout  android:id="@+id/realtabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" />

    <android.support.v4.app.FragmentTabHost  android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/maintab_toolbar_bg">

        <FrameLayout  android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0" />            
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

FragmentPage1,2,3,4,5.java碎片实现

package com.vhreal.myfragmenttest;

import com.vhreal.myfragmenttest.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentPage1 extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_1, null);     
    }   
}

主页面实现MainTabActivity.java

package com.vhreal.myfragmenttest;

import com.vhreal.myfragmenttest.R;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

/** * @author vhreal * 功能描写叙述:自己定义TabHost */
public class MainTabActivity extends FragmentActivity {
    // 定义FragmentTabHost对象
    private FragmentTabHost mTabHost;

    // 定义一个布局
    private LayoutInflater layoutInflater;

    // 定义数组来存放Fragment界面
    private Class fragmentArray[] = { FragmentPage1.class, FragmentPage2.class,
            FragmentPage3.class, FragmentPage4.class, FragmentPage5.class };

    // 定义数组来存放button图片
    private int mImageViewArray[] = { R.drawable.tab_home_btn,
            R.drawable.tab_message_btn, R.drawable.tab_selfinfo_btn,
            R.drawable.tab_square_btn, R.drawable.tab_more_btn };

    // Tab选项卡的文字
    private String mTextviewArray[] = { "首页", "消息", "好友", "广场", "很多其它" };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_layout);

        initView();
    }

    /** * 初始化组件 */
    private void initView() {
        // 实例化布局对象
        layoutInflater = LayoutInflater.from(this);

        // 实例化TabHost对象,得到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        // 得到fragment的个数
        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
            // 为每个Tabbutton设置图标、文字和内容
            TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
                    .setIndicator(getTabItemView(i));
            // 将Tabbutton加入进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            // 设置Tabbutton的背景
            mTabHost.getTabWidget().getChildAt(i)
                    .setBackgroundResource(R.drawable.selector_tab_background);
        }
    }

    /** * 给Tabbutton设置图标和文字 */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);

        return view;
    }
}

执行结果
这里写图片描写叙述这里写图片描写叙述这里写图片描写叙述这里写图片描写叙述这里写图片描写叙述

四、參考引用

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115485.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • HBase面试题总结1「建议收藏」

    HBase面试题总结1「建议收藏」hbase的特点是什么??1)hbase是一个分布式的基于列式存储的数据库,基于Hadoop的hdfs存储,zookeeper管理。2)hbase适合存储半结构化和非结构化数据,对于结构化数据字段不够确定或者杂乱无章很难按一个概念去抽取数据;3)hbase为空的纪录不会被存储;4)基于的表包含rowkey,时间戳,列族,新写入数据时,时间戳更新,同时可以查询到以前的版本;5)hbase是…

    2022年5月8日
    55
  • mac pycharm安装设置_python爬虫 | mac系统PyCharm的安装「建议收藏」

    mac pycharm安装设置_python爬虫 | mac系统PyCharm的安装「建议收藏」视频在之前我们是不是提到了,后面我们要学一个集成的开发环境,就是IDE。全称IntegratedDevelopmentEnvironment,翻译过来集成开发环境。我们经常用PyCharm作为Python开发的IDE,我们以后所有的代码当中可能就要用这个工具去写了。下载我们直接在百度输入,https://www.jetbrains.com/pycharm,进入pycharm安装界面…

    2022年8月26日
    6
  • mysql自定义函数写法_mysql多实例部署

    mysql自定义函数写法_mysql多实例部署本文实例讲述了mysql自定义函数原理与用法。分享给大家供大家参考,具体如下:本文内容:什么是函数函数的创建函数的调用函数的查看函数的修改函数的删除首发日期:2018-04-18什么是函数:函数存储着一系列sql语句,调用函数就是一次性执行这些语句。所以函数可以降低语句重复。【但注意的是函数注重返回值,不注重执行过程,所以一些语句无法执行。所以函数并不是单纯的sql语句集合。】mysql函数有自己…

    2025年10月4日
    2
  • javaweb-springMVC-54

    javaweb-springMVC-54

    2021年5月18日
    155
  • notify() 和 notifyAll() 有什么区别?「建议收藏」

    notify() 和 notifyAll() 有什么区别?「建议收藏」notify()和notifyAll()有什么区别?先解释两个概念。等待池:假设一个线程A调用了某个对象的wait()方法,线程A就会释放该对象的锁后,进入到了该对象的等待池,等待池中的线程不会去竞争该对象的锁。 锁池:只有获取了对象的锁,线程才能执行对象的synchronized代码,对象的锁每次只有一个线程可以获得,其他线程只能在锁池中等待区别:notify()…

    2025年10月8日
    3
  • 钓鱼网站盗QQ_qq看别人的空间一定会被别人知道吗

    钓鱼网站盗QQ_qq看别人的空间一定会被别人知道吗刚刚打开手机tim看到QQ空间有留言下面一个截图的东西(别扫进去输自己的账号密码哈,看看就得了,典型的钓鱼网站)貌似在前几年就有此类网站,不过现在高级了些,下面就由图图来分析一下原理是什么鬼(毫无技术含量)大神快点绕道!!!首先看到这个图片而写是熟人给你留言的,并且还是以好友备注的名字进行留言“XXX,我们合影的照片都在这里了你太好笑了照片呆呆的,长摁识别”会有这么一句话,好奇心强的都会点进去看~【为什么要搞这种二维码呢?就是为了不让一些在线解码的网站轻易识别反而只有QQ、微信可…

    2022年8月24日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号