如何将Android Activity转换为界面? [英] How is it possible to cast an Android Activity to an interface?

查看:136
本文介绍了如何将Android Activity转换为界面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处的Android文档中: http://developer.android.com/guide/ components / fragments.html Fragment实现了一个接口。

In the Android documentation here: http://developer.android.com/guide/components/fragments.html A Fragment implements an interface.

在onAttach()回调中,似乎将当前的Activity转换为接口。从概念上讲,这是如何实现的,并且是与vanilla Java中相同类型的强制标准实践?

In the onAttach() callback, it seems to cast the current Activity to an interface. Conceptually, how is this possible and is the same type of cast standard practice in vanilla Java?

public static class FragmentA extends ListFragment {


// Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);


    OnArticleSelectedListener mListener;



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
    ...
}


推荐答案

关于该主题的一些基本知识:

Some basic knowledge about the topic:

想想界面作为一组功能。如果实现接口,那么它保证它已实现所有接口函数。

Think about an interface as a bundle of functions. If a class implements an interface, then it guarantees, that it has all the interfaces functions implemented.

在你的情况下:

如果你有一个对象并且你不需要更多的接口功能,那么您的对象实现,然后您可以将该对象处理(并转换)到该接口。这样你就会丢失关于你的对象的信息,因为你将无法使用它的功能(除了接口函数),但有时它足够了。

If you have an object and you don't need more than the functions of an interface, that your object implements, then you can treat (and cast) that object to that interface. This way you loose "information" about your object, because you won't be able to use its functions (except the interface functions), but sometimes its enough.

这篇关于如何将Android Activity转换为界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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