安卓Fragment中的Button如何设置事件处理?

安卓Fragment中的Button如何设置事件处理?,第1张

首先,你需要重写Fragment类的onCreateView方法,并找到根View,因为你的按钮是属于根View的。然后对根View使用源州findViewById()方法找到按钮,并为按钮设置监听器。

最後,别忘记返回根View。

代码如下:

@Override

public View 毁丛onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment, container, false)

    Button button = 纤裂樱(Button) rootView.findViewById(R.id.button)

    button.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

        //处理监听事件

    }

})

    return rootView

}

希望以上内容能帮助到您,满意请采纳,欢迎追问!

需要做的准备

新建一个android项目,主Activity命名为MainActivity

创建三个Fragment1 Fragment2 Fragment3

为三个Fragment创磨睁建三个布局文fragment1.xml、fragment2.xml、fragment3.xml

布局 activity_main.xm

fragment1.xml样例

Fragment1样例

另外的可以根据样例进行修改

activity_main.xml内容

activity打开时需要显示一个fragment,也就是需要先向容器中添加一个fragment

这是就能显示第二个fragment了,那么如何切换不同链拦的fragment呢,切换的过程如下

开启事务

调用事务的replace方法,将当前容器的fragment替换为新的fragment

提交事务

注意上图红框中的addToBackStack方法,很多人都不是很清楚这个方法的实际作用,说一下程序运行时候的现象你就明白了

初始化时显示的是 fragment2

实践棚游胡1 :fragment2------点击按钮frag1-----按返回键--------退出应用

实践2: fragment2-----点击按钮frag3 -----按返回键--------返回到fragment2

为啥会出现上面的情况,原因就是切换到fragment3时,调用了addToBackStack方法,这时会将fragment2先入栈,然后再切换到fragment3,按返回键的时候fragment3销毁,fragment2出栈显示,而切换到fragme1时没有将fragme2入栈,所以fragment2就直接销毁了,再按返回键就直接退出应用了


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12331955.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存