2013-03-19 2 views
1

기본적으로 BroadCaseReciever 안에 TextView 클래스의 setText() 기능을 수행하고 싶습니다. 하지만 난이를 구현 할 수 없다는 오전 : 내가BroadCastReciever의 onRecieve 메소드 안에 TextView의 텍스트를 설정하는 방법은 무엇입니까?

이유 (context.findviewById()가 작동하지 않습니다) 잘 모릅니다, findViewById()이 활동 클래스의 일부이며 context.toString()은 (기본 활동) 클래스 활동의 기준을 보여주고 있기 때문에?

답변

2

링크 : Communicating with Other Fragments

이 조각이 활동까지 통신 할 수 있도록하려면, 당신은 조각 클래스의 인터페이스를 정의하고 활동 내에서 구현할 수 있습니다. Fragment는 onAttach() 라이프 사이클 메소드에서 인터페이스 구현을 캡처 한 다음 Activity와 통신하기 위해 Interface 메소드를 호출 할 수 있습니다. 여기

활동 통신에 조각의 예이다 :

공용 클래스 HeadlinesFragment가 ListFragment { OnHeadlineSelectedListener mCallback 확장;

// Container Activity must implement this interface 
public interface OnHeadlineSelectedListener { 
    public void onArticleSelected(int position); 
} 

@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"); 
    } 
} 

... 

} 이제 OnHeadlineSelectedListener 인터페이스 mCallback 인스턴스를 사용 onArticleSelected() 메소드 (또는 다른 인터페이스 방식)를 호출하여 활성에 메시지를 전달할 수있는 단편.

예를 들어 사용자가 목록 항목을 클릭하면 다음 조각이 호출됩니다. 프래그먼트는 콜백 인터페이스를 사용하여 상위 액티비티에 이벤트를 전달합니다.

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    // Send the event to the host activity 
    mCallback.onArticleSelected(position); 
} 

는 조각에서이 조각 클래스에 정의 된 인터페이스를 구현해야 호스팅 활동을 이벤트 콜백을 받기 위해서는 인터페이스 를 구현합니다.

예를 들어, 다음 활동은 위 예의 인터페이스를 구현합니다.

공용 정적 클래스 MainActivity 활동 가 HeadlinesFragment.OnHeadlineSelectedListener { ...

public void onArticleSelected(int position) { 
    // The user selected the headline of an article from the HeadlinesFragment 
    // Do something here to display that article 
} 

} 조각 위치 인스턴스를 캡쳐하여 조각 로 프래그먼트으로 메시지를 전달할 수있는 호스트 활동 메시지 전달을 구현 연장 findFragmentById()를 사용하여 직접 프래그먼트의 public 메소드를 호출하십시오.

예를 들어 위의 활동에 위의 콜백 메소드에서 반환 된 데이터로 지정된 항목을 표시하는 데 사용되는 다른 단편이있을 수 있다고 가정 해보십시오.이 경우, 액티비티가 항목을 표시 다른 단편 콜백 방법에서 수신 된 정보를 전달할 수

공용 정적 클래스 MainActivity 연장 활동 는 { ...

public void onArticleSelected(int position) { 
    // The user selected the headline of an article from the HeadlinesFragment 
    // Do something here to display that article 

    ArticleFragment articleFrag = (ArticleFragment) 
      getSupportFragmentManager().findFragmentById(R.id.article_fragment); 

    if (articleFrag != null) { 
     // If article frag is available, we're in two-pane layout... 

     // Call a method in the ArticleFragment to update its content 
     articleFrag.updateArticleView(position); 
    } else { 
     // Otherwise, we're in the one-pane layout and must swap frags... 

     // Create fragment and give it an argument for the selected article 
     ArticleFragment newFragment = new ArticleFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ArticleFragment.ARG_POSITION, position); 
     newFragment.setArguments(args); 

     FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

     // Replace whatever is in the fragment_container view with this fragment, 
     // and add the transaction to the back stack so the user can navigate back 
     transaction.replace(R.id.fragment_container, newFragment); 
     transaction.addToBackStack(null); 

     // Commit the transaction 
     transaction.commit(); 
    } 
} 
HeadlinesFragment.OnHeadlineSelectedListener는 구현

}

+0

callback() 개념을 사용했습니다. – Tushar

0

BroadcastReceiver가 활동 컨텍스트 내에서 프로그래밍 방식으로 시작되는 경우를 제외하고. Activity.onCreate(). 일반 BroadcastReceiver의 경우 TextView와 같은 UI 요소에 액세스하는 것은 매우 이상합니다. 액티비티의 UI 요소로만 작업 할 수 있습니다. 어쩌면 당신이 적용하려고하는 솔루션을 검토해야 할 것입니다. 당신이 그런 일을 할지라도 틀린 디자인이 될 것입니다. 대답은 여기 아래에

+0

죄송합니다 ...하지만 난 (AsyncTask를)를 사용하여 인터넷에서 뭔가를 가져 지금 내가 텍스트 뷰에 데이터를 보내려면, 같은 일을하고, 그래서 난 데이터 어를 설정하는 broadcast_reciever을 사용하고 대답 ich는 인터넷에서 가져온 것입니다. – Tushar

+0

그런 다음 BroadcastReceiver가 필요하지 않습니다 ... onPostExecute() 메서드에서 모두 수행하십시오 ... 물론 doInBackground가 필요한 데이터를 반환하는지 확인한 다음 textView.setText() 이 경우 특별히 설계된 onPostExecute() 내에서 호출 ... UIThread에서 실행됩니다. 그것이하는 방법입니다. –

+0

당신은 사실입니다 ...하지만 지금은 그 fragment 안에 조각이 있다고 생각합니다. textView를 가지고 있습니다. (당신의 대답 Rock을 조각 내지 않고) 이제는 Fragment's_textView 안에 어떻게 Text를 설정할 수 있을까요? – Tushar

0
public class MyReceiver extends BroadcastReceiver { 

private MyActivity myActivity; 

public MyReceiver(MyActivity myActivity) { 
    this.myActivity= myActivity; 
} 

@Override 
public void onReceive(Context context, Intent intent) { 

    Log.d("", "Onrecieve ready to call"); 
      if(this.myActivity!=null) 
      { 
       this.myActivity.update(); 
      } 
      // make update method is in your activity. 
      // call function of your activity and change UI. 
} 
} 
+0

BroadcastReceiver에서 액티비티가 새어 나오지 않습니다 ... 액티비티가 죽을 수 있고 BroadcastReceiver가 죽은 액티비티에 대한 참조를 누출하게됩니다 ... 이것은 옵저버 패턴을 적용하는 일반적인 경우입니다. –

+0

만약 활동이 죽었다면 ..'TextView' 질문에 텍스트를 설정하는 것이 발생하지 않습니다. 활동이 죽은 경우 수신자 등록을 취소하십시오 –

+0

@Alecio, 와우 그 훌륭한 답변, 나는 그렇게 생각하지 않습니다. 그것의 vote_up 대답. – Tushar

관련 문제