什么是碎片和活动之间的核心区别是什么?其中code可以写成片段? [英] What's the core difference between fragment and activity? Which code can be written in fragment?

查看:279
本文介绍了什么是碎片和活动之间的核心区别是什么?其中code可以写成片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个选项卡,每个三个片段,一个主要活动,我想创建发送过来wifi网络信息插座,所以我应该在哪里写的code呢?在那个特定的片段类或主要活动?

I have three tabs with three fragments each and one main activity, and i want to create the socket to send the message over wifi network, so where should i write the code for it? In that particular fragment class or main activity?

推荐答案

当然,你可以写片段内的任何code,但你需要采取一些后事。虽然访问特定于活动任何需要上下文或东西,你需要获得一个参考片段,如超级活动而创建活动内部的意图,你做这样的事情:

Of course you can write any code inside the fragment but you need to take care of a few things. While accessing anything that requires a context or something that is specific to an activity you will need to get a reference to the super activity of the fragment, e.g. while creating an intent inside an activity you do something like this :

    Intent intent = new Intent(this,SomeActivity.class);

但一个片段里,你将不得不做这样的事情:

but inside a fragment you will have to do something like this:

    Intent intent = new Intent(super.getActivity(),SomeActivity.class);

如果同样你是从碎片的布局文件访问某些事情。您需要执行以下步骤:

Similarly if you are accessing some thing from the layout file of the fragment. You need to perform the following steps:

1)获得一个全局引用您的片段父布局的片段中。例如

1)get a global reference to the parent layout of your fragment inside your fragment. e.g

    private LinearLayout result_view;

2)实施OnCreateView方法,而不是onCreate方法。

2) Implement the OnCreateView method instead of onCreate method.

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

        return result_view;
    }

3)充气像这样的片段布局片段的onCreateView方法中:

3) Inflate the fragment layout like this inside the onCreateView method of the fragment:

    result_view = (LinearLayout) inflater.inflate(
            R.layout.image_detail_pager, container, false);

4)你现在可以访问这样的布局的观点:

4) you can now access layout views like this :

    layout_a = (LinearLayout) result_view
            .findViewById(R.id.some_layout_id); 

这篇关于什么是碎片和活动之间的核心区别是什么?其中code可以写成片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆