-3
mCallback = (OnHeadlineSelectedListener) activity;

这是 android 应用教程的一些 java 代码。我不明白这到底在做什么。我知道它正在为 mCallback 赋值,但是什么?为什么 OnHeadlineSelectedListener 在括号中,然后活动对象就在它后面,到底是什么?

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.vizoplex.my.first.app;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }
}
4

6 回答 6

2

那就是类型转换。例如:你有两个方法的 Animal 接口,运行和吃。

public interface Animal {
    public String run();
    public String eat(String food);
}

你有实现它的类,比如 Cat 类。Cat 类有一些额外的方法,scratch 和 mew。

public class Cat implements Animal{
   public String run(){
     return "Run as a cat";
   }
   public String eat(){
     return "Eat fish";
   }
   public String mew(){
     return "MEW!!!!";
   }
   public String scratch(){
     return "scratch-scratch-scratch";
   }
}

另外,你有 Dog 类,它有 bark 方法。

public class Dog implements Animal{
   public String run(){
     return "Run as a dog";
   }
   public String eat(){
     return "Eat meat";
   }
   public String bark(){
     return "BARK!!!!";
   }
}

所以,很多时候你需要和你的动物一起工作,就像和一些确切的动物(狗或猫)一起工作。但是没有你的帮助,编译器 cat 不会进行这种转换。所以,你必须告诉它你到底想要什么:

public void Show{
  Cat cat = new Cat(); //you have a cat
  Dog dog = new Dog(); //and a dog
  Animal animal = null; //and animal
  dog = (Dog)animal; //and here is where compiler can't convert animal to dog without your help.
  Animal animal2 = cat; //But this casting it can make without your help, as it exactly knows what to do.
}

这本书对学习Java非常有用。如果你真的有兴趣了解这些东西,你应该阅读它。在这本书中也可以找到关于铸造如何工作的完整解释。

于 2012-10-30T20:10:46.320 回答
2

它试图将该活动转换为OnHeadlineSelectedListener,可能是因为该实际活动扩展了该Listener。这样,mCallback 充当了正确定义回调的侦听器。

编辑

你有:

try {
    mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
    throw new ClassCastException(activity.toString()
            + " must implement OnHeadlineSelectedListener");
}

它正在尝试转换activityOnHeadlineSelectedListener. 如果activity未实现此侦听器,则会引发异常。该消息非常简单:

activity.toString()+ " must implement OnHeadlineSelectedListener"
于 2012-10-30T18:56:55.680 回答
1

我认为 mCallback 对象是活动对象类的子类。所以这个语句将活动对象转换为更具体的 mCallback 对象。

有关铸造的更多信息,请单击此处

于 2012-10-30T18:58:01.803 回答
1

activity正在被强制转换为一个正在分配的OnHeadlineSelectedListener对象。mCallback

于 2012-10-30T18:56:04.000 回答
0

它将活动转换为 OnHeadlineSelectedListener。假设活动实现了 OnHeadlineSelectedListener。这样做是为了让您可以直接调用接口 OnHeadlineSelectedListener 中的方法。

于 2012-10-30T18:56:34.723 回答
0

我最近从 Java 中过渡出来,但在我看来,那条线好像正在转换 activity为 type OnHeadlineSelectedListener。强制转换将一种类型转换为另一种类型,如果类型不兼容,则抛出异常(一种或另一种形式)。

语法是这样的:

variable = (Type) variableOfType2;
于 2012-10-30T18:57:25.263 回答