• Android学习第八天


      Fragment是什么

      Fragment是一种可以嵌入在Activity当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间,因 而在平板上应用得非常广泛。

      虽然Fragment对你来说是个全新的概念,但我相信你学习起来应该毫不费力,因为它和Activity实在是太 像了,同样都能包含布局,同样都有自己的生命周期。

      你甚至可以将Fragment理解成一个迷你型的Activity,虽然这个迷你型的Activity有可能和普通的Activity是 一样大的.

      新建一个左侧Fragment的布局left_fragment.xml,再新建一个右侧Fragment的布局right_fragment.xml,
      代码如下所示:

      

    <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>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#00ff00"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:textSize="24sp"
    android:text="This is right fragment"
    />
    </LinearLayout>

    然后编写LeftFragment和RightFragment中的代码,如下所示:
    class LeftFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.left_fragment, container, false)
    }
    }
    class RightFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.right_fragment, container, false)
    }
    }

    接下来修改activity_main.xml,在布局中引入Fragment。
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <fragment
    android:id="@+id/leftFrag"
    android:name="com.example.fragmenttest.LeftFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />
    <fragment
    android:id="@+id/rightFrag"
    android:name="com.example.fragmenttest.RightFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />
    </LinearLayout>

    运行效果:

  • 相关阅读:
    并查集
    结构体字节对齐
    Dijkstra算法(单源最短路径)
    图的遍历
    二叉树的非递归遍历
    浅谈C语言中的联合体
    二叉排序(查找)树
    KMP算法
    C语言文件操作解析(四)
    Trie树
  • 原文地址:https://www.cnblogs.com/yongyuandishen/p/14867233.html
Copyright © 2020-2023  润新知