2016-06-02 3 views
1

MainActivity에는 myFragment라는 조각이 있습니다. ViewPagerAdapter를 사용하여 Fragment를 호출하는데, 이는 정상적으로 작동합니다.Fragment를 CustomArrayAdapter 생성자에 전달하는 방법

MyFragment를 CustomArrayAdapter에 전달하려고하는데 내 응용 프로그램이 수퍼 클래스를 호출 할 때 생성자에서 충돌합니다.

여기 내 코드입니다 :

public class MyFragment extends Fragment implements MyInterface { 

    public MyFragment() {} 

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

    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment_paired_device, container, false); 
    } 

    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     Row[] arrList = new Row[5]; 

     // THE FOLLOWING LINE IS SUPPOSED TO PASS THE FRAGMENT 
     CustomAdapter myCustomAdapter = new CustomAdapter((MyInterface) this.getActivity(), arrList); 
    } 
} 

CustomAdapter.java

public class CustomAdapter extends ArrayAdapter<Row> { 
    Row[] rowItems = null; 
    MyInterface myFragment; 

    public CustomAdapter(MyInterface myFragment, Row[] resource) { 
     // THE FOLLOWING LINE THROWS AN ERROR 
     super((FragmentActivity) myFragment, R.layout.row_with_cb, resource); 
     this.rowItems = resource; 
     this.myFragment = myFragment; 
    } 

    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 
    } 
} 

MyFragment.java 나는 다음과 같은 오류 얻을 : 어떤 이유

java.lang.ClassCastException: MainActivity cannot be cast to MyInterface 

을, this.getActivity는 su입니다. FragmentActivity를 보내기 위해 대기하지만 MainActivity를 보냅니다.

누구든지 나를 도와 줄 수 있습니까? 당신은 현재 MyFragment가 부착되어 Activity 되었하려고

+0

패스'대신'(하는 MyInterface) this.getActivity()의 this'' –

+0

가합니까''FragmentActivity'을 확장 MainActivity' 어댑터? – PPartisan

+0

감사합니다. @shayanpourvatan – AyeVeeKay

답변

0

I am trying to pass MyFragment to a CustomArrayAdapter but my application crashes at the constructor when it calls the super class.

하지 Fragment 자체 : 당신을 "캐스트"는 Activity을 시도하기 때문에이 ClassCastException을 받고있는 이유는

CustomAdapter myCustomAdapter = new CustomAdapter((MyInterface) this.getActivity(), arrList); 

getActivity() 메서드 호출 (이 경우 MainActivity)에서 (MyInterface)으로 반환됩니다. MainActivityMyInterface을 구현하지 않으므로 예외가 발생합니다.

달성하려는 목표가 실제로 명확하지 않습니다. 그의 답변에서 Eugen이 지적한 것처럼 기본 ArrayAdapter 생성자는 Context 인수를 취합니다. MyInterface 또는 MyFragmentContext의 예가 아닙니다. 단, Activity이며Context입니다. 따라서 다음과 같은 수퍼 호출은 이해할 수 없습니다.

public CustomAdapter(MyInterface myFragment, Row[] resource) { 
    super((FragmentActivity) myFragment, R.layout.row_with_cb, resource); 
} 

따라서 Activity을 여기에 전달해야합니다. 당신은 여전히 ​​Interface을 통과하려는 경우, 다음과 같이 귀하의 생성자를 조정할 수 :

private MyInterface myInterface;  

public CustomAdapter(Context context, Row[] rows, MyInterface myInterface){ 
    super(context, R.layout.row_with_cb, rows); 
    this.myInterface = myInterface; 
} 

나는 당신이 실제로 통과 할 것인지 확실하지 않다 당신의 Fragment 또는 그러나 귀하의 질문에서 어댑터에 MyInterface.

0

어레이 어댑터에는 컨텍스트가 필요합니다 (조각이 아님). 다음에

변경을 : 활동의

public CustomAdapter(Context context, Row[] resource) { 
     super(context, R.layout.row_with_cb, resource); 
     ... 
} 

그리고 제거 주조 :

CustomAdapter myCustomAdapter = new CustomAdapter(this.getActivity(), arrList); 
0

달성하기 위해 노력하고 시나리오는 질문 자체보다 조금 더 복잡하다.

this 및 this.getContext()를 CustomAdapter 생성자에 전달하여 문제를 해결했습니다. Shayan과 PPartisan이 언급했듯이 Context만으로도 ArrayAdapter 생성자로 보낼 수있었습니다.

Fragment의 관점에서 this.getActivity()는 현재 Fragment의 'FragmentActivity'를 산출 할 것으로 예상됩니다 (MainActivity 여야하는지 확실하지 않음). CustomAdapter의 수퍼 클래스에 유효한 인수이지만 반환하지는 않습니다. (왜 이런 일이 일어나는 지 아직 확실하지 않습니다.) 이것이 제가 캐스팅을 시도한 이유입니다.

내가 조각 자체를 필요로하는 이유는 myInterface로 선언되고 Fragment에 의해 구현 된 메서드를 호출하는 콜백 메서드 (CustomAdapter 내부)가 있기 때문입니다.

지금은 모두 정상입니다.

감사

관련 문제