设置侦听器接口时出现ClassCastException

时间:2013-07-21 07:33:27

标签: android interface listener actionlistener

尝试设置自定义侦听器,以将活动中的字符串发送到该活动内部的片段。按下Activity按钮,文本字符串应该发送到片段并显示在该片段的textview中,但是我得到一个classCastException并且不知道该怎么做。你怎么能让这个工作?

错误在这一行

 listener = (OnStringRequestedListener) fragment;

我不知道如何在没有该行代码的情况下设置此自定义侦听器接口。我使用类似的代码行向相反的方向运行。那是或者从片段发送消息到Activity。然而,我今天所尝试的是无法正常工作

堆栈跟踪

Caused by: java.lang.ClassCastException:
com.example.asynctaskprogressbarexample.InterfaceActivityToFragmentFragment
cannot be cast to com.example.asynctaskprogressbarexample
.InterfaceActivityToFragment$OnStringRequestedListener
at com.example.asynctaskprogressbarexample
.InterfaceActivityToFragment.onCreate(InterfaceActivityToFragment.java:27)

活动类

  public class InterfaceActivityToFragment extends Activity {

Button buttonOne;
private OnStringRequestedListener listener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.interface_activity_to_fragment);

    Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment1);

    listener = (OnStringRequestedListener) fragment; // <-- ERROR ON THIS LINE

     if (fragment instanceof OnStringRequestedListener) {
          listener = (OnStringRequestedListener) fragment;
        } else {
          throw new ClassCastException(fragment.toString()
              + " must implemenet OnTimeRequestedListener");
        }

    buttonOne = (Button) findViewById(R.id.button1);

    buttonOne.setOnClickListener(new Button.OnClickListener(){

           @Override
           public void onClick(View v) {
            // TODO Auto-generated method stub
              listener.passString("string from Activity");

           }

        });

}

public interface OnStringRequestedListener {
    public void passString(String sendNumberString);

  }

 }

片段类

 public class InterfaceActivityToFragmentFragment extends Fragment implements FragmentHeadlessAsyncTaskFragment.OnStringRequestedListener {

TextView textViewOne;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    View view = inflater.inflate(R.layout.interface_activity_to_fragment_fragment, container, false);

    TextView textViewOne = (TextView) view.findViewById(R.id.textView1);

    return view;
} // end on create view

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

  setRetainInstance(true);
 }

@Override
public void passString(String stringFromActivity) {
     textViewOne.setText(stringFromActivity);

}
  }

1 个答案:

答案 0 :(得分:3)

您正在实施FragmentHeadlessAsyncTaskFragment.OnStringRequestedListener,但已转为InterfaceActivityToFragment.OnStringRequestedListener

定义为嵌套在两个不同类中的相同接口。