android开发,使用kotlin学习Fragment
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
1.Fragment的介绍
Android在3.0版本引入了Fragment功能它非常类似于Activity可以像Activity一样包含布局。
它出现的初衷是为了适应大屏幕的平板电脑使用Fragment我们可以把屏幕划分成几块合理利用屏幕空间。
Fragment通常是嵌套在Activity中使用。
2.静态加载
步骤
1定义Fragment控件的布局文件。
<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=".LeftFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是左边" />
</FrameLayout>
<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=".RightFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是右边" />
</FrameLayout>
2自定义Fragment类继承自Fragment类或者子类同时实现onCreateView方法在方法中通过inflater.inflate加载布局文件接着返回其View。
class LeftFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_left, container, false)
}
}
class RightFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_right, container, false)
}
}
3在需要加载Fragment控件的Activity对应的布局文件中添加Fragment标签并设置name属性为自定义fragment。
<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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/leftFrag"
android:name="com.hui.fragment.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<fragment
android:id="@+id/rightFrag"
android:name="com.hui.fragment.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
4最后在Activity的onCreate方法中调用setContentView加载布局。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
3.动态加载
步骤
1通过getSupportFragmentManager方法获得FragmentManager对象。
val fragmentManager=supportFragmentManager
2开启事务通过beginTransaction方法获得FragmentTransaction对象。
val transaction=fragmentManager.beginTransaction()
3调用add方法或者repalce方法加载Fragment。
transaction.replace(R.id.rightLayout,fragment)
//replace()方法需要传入容器的id和待添加的Fragment实例
4最后调用commit方法提交事务。
transaction.commit()