我们编写一个能够用过按钮动态更替碎片的APP,首先在主页上显示第一个碎片,点击按钮后可以替换到第二个碎片,或者删除已经替换掉的第二个碎片。

一.MainActivity.java

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction; import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button; public class MainActivity extends FragmentActivity { public MainActivity() {
Log.e("TAG", "MainActivity()..");
} @Override
protected void onCreate(Bundle savedInstanceState) {
Log.e("TAG", "MainActivity onCreate()..");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//重写onCreate()方法 // 创建Fragment对象
final MyFragment1 fragment1 = new MyFragment1();
// 得到FragmentManager
FragmentManager manager = getSupportFragmentManager();
// 得到FragmentTransacation
FragmentTransaction transaction = manager.beginTransaction();
// 添加Fragment对象并提交
transaction.add(R.id.ll_main, fragment1).commit(); Button button1=(Button)findViewById(R.id.fragment_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showFragment2();
}
});
Button button2=(Button)findViewById(R.id.fragment_2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
deleteFragment2();
}
}); }
private MyFragment2 fragment2;
public void showFragment2() {
// 创建Fragment对象
fragment2 = new MyFragment2();
// 得到FragmentManager
FragmentManager manager = getSupportFragmentManager();
// 得到FragmentTransacation
FragmentTransaction transaction = manager.beginTransaction(); //将当前操作添加到回退栈, 这样点击back回到上一个状态
transaction.addToBackStack(null); // 替换Fragment对象并提交
transaction.replace(R.id.ll_main, fragment2).commit();
}
public void deleteFragment2() { // 得到FragmentManager
FragmentManager manager = getSupportFragmentManager();
// 得到FragmentTransacation
FragmentTransaction transaction = manager.beginTransaction();
// 移除Fragment对象并提交
transaction.remove(fragment2).commit();
}
}

二.activity_main.xml

<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button android:id="@+id/fragment_1"
android:text="切换至第二个碎片"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:id="@+id/fragment_2"
android:text="删除第二个碎片"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_main"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"> </LinearLayout>
</LinearLayout>

编写好的界面如下图所示:

三.MyFragment1.java

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class MyFragment1 extends Fragment { public MyFragment1() {
// Required empty public constructor
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); } @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my_fragment1, container,false);
} }

四.MyFragment2.java

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class MyFragment2 extends Fragment {
public MyFragment2() {
// Required empty public constructor
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); } @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my_fragment2, container,false);
} }

五.fragment1.xml

<?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=".MyFragment1"> <!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是第一个碎片" /> </FrameLayout>

六.fragment2.xml

<?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=".MyFragment2"> <!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是第二个碎片" /> </FrameLayout>

完毕

Android动态添加碎片的更多相关文章

  1. Android — — —动态添加碎片

    <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=" ...

  2. Android中如何动态添加碎片

    Android中的开发需要兼容手机和平板,两个方面.这就引入了碎片的概念.(注意:这里用的Fragment强烈建议使用support-v4库中的Fragment) 碎片:是一种可以嵌入在活动当中的UI ...

  3. Android动态添加Device Admin权限

    /********************************************************************** * Android动态添加Device Admin权限 ...

  4. Android 动态添加Spinner(.java文件内实现) 实现 改变spinner 内文字属性

    动态添加spinner 控件 Spinner s = new Spinner(this); String []items={"自己定义的要显示的数组"}; my_SpinnerAd ...

  5. Android动态添加和移除布局

    package com.hyang.administrator.studentproject; import android.os.Bundle; import android.support.v7. ...

  6. android动态添加TextView或者ImageView

    动态添加 text1=new TextView(this); text1.setText("动态添加"); ((LinearLayout) this.findViewById(R. ...

  7. Android -- 动态添加布局

    在做项目的时候,遇到了scrollView与listView结合的使用,导致了滑动的混乱,但是有一个办法可以解决掉这个问题,就是手写listView的高度,还有另外一种方法,传送门:<Andro ...

  8. Android 动态添加删除ExpandableListView的item的例子

    这个例子可以学习到如下几点: 1.通过自定义Dialog(单独布局的xml文件进行弹出显示) 2.通过menu点击监听添加,删除view中的items 3.点击ExpandableListView中g ...

  9. Android动态添加布局

    //1.利用LayoutInflater的inflate动态加载XML mLinearLayout = (LinearLayout)findViewById(R.id.LinearLayout_ID) ...

随机推荐

  1. day 25 方法和函数 反射

    特殊成员的补充: # __str__ class Foo(object): def __init__(self): pass def func(self): pass def __str__(self ...

  2. UiPath之获取邮件相关信息

    大家好,小U又来给大家分享UiPath文章,争取每一篇文章都给大家带来满满的干货. 本次案例是告诉大家如何使用GetOutLookMailMessage这个Activity, 案例的目的是将某个特定人 ...

  3. 使用最新AndroidStudio编写Android编程权威指南(第3版)中的代码会遇到的一些问题

    Android编程权威指南(第3版)这本书是基于Android7.0的,到如今已经过于古老,最新的Android版本已经到10,而这本书的第四版目前还没有正式发售,在最近阅读这本书时,我发现这本书的部 ...

  4. P1046 陶陶摘苹果

    题目描述 陶陶家的院子里有一棵苹果树,每到秋天树上就会结出1010个苹果.苹果成熟的时候,陶陶就会跑去摘苹果.陶陶有个3030厘米高的板凳,当她不能直接用手摘到苹果的时候,就会踩到板凳上再试试. 现在 ...

  5. PringData JPA一对多多对一多对多关联

    一.一对多.多对一 1.Country实体类 2.City实体类 3.CountryDao层 4.CityDao层 5.Controller package com.zn.controller; im ...

  6. 二叉树的建立&&前中后遍历(递归实现)&&层次遍历

    下面代码包含了二叉树的建立过程,以及三种遍历方法了递归实现,代码中还利用队列实现了层次遍历. import java.util.LinkedList; import java.util.Queue; ...

  7. 前端跨域 nginx 反向代理

    1.下载ngnix稳定版   (http://nginx.org/en/download.html) 2.解压到你中意的目录. 3.将你的网页文件放到刚解压html文件目录下 4.打开conf  &g ...

  8. 使用g++编译器扩大程序可用栈空间

    如题,在写一些程序的时候我们有时会开一个比较大的数组或进行层数较多的dfs.这时候,程序常常会报错,于是就很无奈. 其实,虽然Windows给程序的默认栈空间比较小,我们还是有办法去扩大这个程序运行栈 ...

  9. promise 进阶 —— async / await 结合 bluebird

    一.背景 1.Node.js 异步控制 在之前写的 callback vs async.js vs promise vs async / await 里,我介绍了 ES6 的 promise 和 ES ...

  10. wow钓鱼方案

    最近怀旧服启动了 玩(排)得我萎靡不堪 突然想起多年前写过一个钓鱼的按键精灵 赶紧搜出来助我一臂之力 奈何往年不知其珍贵 早不见了 千思万想才在群空间的文件夹内翻出来一个exe版本 而源代码已不知去向 ...