IT story

조각과 활동 간의 통신-모범 사례

hot-time 2021. 1. 6. 20:21
반응형

조각과 활동 간의 통신-모범 사례


이 질문은 주로 내 앱을 처리하는 가장 좋은 방법에 대한 의견을 구하는 것입니다. 하나의 활동에서 세 개의 조각을 처리하고 있습니다. 조각 A에는 사진에 클릭 가능한 요소가 1 개 있고 조각 B에는 단추에 클릭 가능한 요소 4 개가 있습니다. 다른 조각은 사진을 클릭하면 세부 정보 만 표시합니다. ActionBarSherlock을 사용하고 있습니다.

스크린 샷

앞으로 및 뒤로 버튼은 각각 다음 또는 이전 포즈로 사진을 변경해야합니다. 사진과 버튼을 같은 조각에 보관할 수 있지만 태블릿에서 재 배열하려는 경우를 대비하여 따로 보관하고 싶었습니다.

조언이 필요합니다. Fragments A와 B를 결합해야합니까? 그렇지 않은 경우 3 개의 클릭 가능한 항목에 대한 인터페이스를 구현하는 방법을 알아 내야합니다.

Roboguice를 사용하는 것을 고려했지만 이미 SherlockFragmentActivity를 사용하여 확장하고 있으므로 그렇게 할 수 없습니다. Otto에 대한 언급을 보았지만 프로젝트에 포함하는 방법에 대한 좋은 자습서는 보지 못했습니다. 최고의 디자인 관행이 무엇이어야한다고 생각하십니까?

또한 프래그먼트와 활동 간의 통신 방법을 알아내는 데 도움이 필요합니다. 포즈 ID와 같은 일부 데이터를 응용 프로그램에 "전역"으로 유지하고 싶습니다. 주식 안드로이드 개발자 정보 외에 볼 수있는 예제 코드가 있습니까? 그게 도움이되지는 않습니다.

BTW, 나는 이미 각 포즈에 대한 모든 정보를 SQLite 데이터베이스에 저장하고 있습니다. 그것은 쉬운 부분입니다.


활동과 프래그먼트간에 통신하는 가장 쉬운 방법은 인터페이스를 사용하는 것입니다. 아이디어는 기본적으로 주어진 조각 A 내부에 인터페이스를 정의하고 활동이 해당 인터페이스를 구현하도록하는 것입니다.

해당 인터페이스를 구현하면 재정의하는 메서드에서 원하는 모든 작업을 수행 할 수 있습니다.

인터페이스의 또 다른 중요한 부분은 프래그먼트에서 추상 메서드를 호출하고이를 액티비티에 캐스팅해야한다는 것입니다. 올바르게 수행되지 않으면 ClassCastException을 잡아야합니다.

이러한 종류의 작업을 정확히 수행하는 방법 에 대한 간단한 개발자 블로그좋은 자습서가 있습니다 .

이 정보가 도움이 되었기를 바랍니다.


프래그먼트 간 통신을위한 제안 된 방법은 기본 활동에서 관리하는 콜백 / 리스너를 사용하는 것입니다.

이 페이지의 코드는 매우 명확하다고 생각합니다. http://developer.android.com/training/basics/fragments/communicating.html

사실상 참조 앱으로 설계된 IO 2012 일정 앱을 참조 할 수도 있습니다. http://code.google.com/p/iosched/ 에서 찾을 수 있습니다 .

또한 여기에 좋은 정보가있는 SO 질문이 있습니다. 조각간에 데이터를 전달하는 방법


콜백 인터페이스로 구현됩니다.

먼저 인터페이스를 만들어야합니다.

public interface UpdateFrag {
     void updatefrag();
}

활동에서 다음 코드를 수행하십시오.

UpdateFrag updatfrag ;

public void updateApi(UpdateFrag listener) {
        updatfrag = listener;
}

콜백이 활동에서 발생해야하는 이벤트에서 :

updatfrag.updatefrag();

조각에서 인터페이스를 구현 CreateView하려면 다음 코드 수행하십시오.

 ((Home)getActivity()).updateApi(new UpdateFrag() {
        @Override
        public void updatefrag() {
              .....your stuff......
        }
 });

캐스트를 할 수있는 주석 라이브러리를 만들었습니다. 이것 좀 봐. https://github.com/zeroarst/callbackfragment/

@CallbackFragment
public class MyFragment extends Fragment {

    @Callback
    interface FragmentCallback {
       void onClickButton(MyFragment fragment);
    }    
    private FragmentCallback mCallback;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt1
                mCallback.onClickButton(this);
                break;
            case R.id.bt2
                // Because we give mandatory = false so this might be null if not implemented by the host.
                if (mCallbackNotForce != null)
                mCallbackNotForce.onClickButton(this);
                break;
        }
    }
}

It then generates a subclass of your fragment. And just add it to FragmentManager.

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager().beginTransaction()
            .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), "MY_FRAGM")
            .commit();
    }

    Toast mToast;

    @Override
    public void onClickButton(MyFragment fragment) {
        if (mToast != null)
            mToast.cancel();
        mToast = Toast.makeText(this, "Callback from " + fragment.getTag(), Toast.LENGTH_SHORT);
        mToast.show();
    }
}

To communicate between an Activity and Fragments, there are several options, but after lots of reading and many experiences, I found out that it could be resumed this way:

  • Activity wants to communicate with child Fragment => Simply write public methods in your Fragment class, and let the Activity call them
  • Fragment wants to communicate with the parent Activity => This requires a bit more of work, as the official Android link https://developer.android.com/training/basics/fragments/communicating suggests, it would be a great idea to define an interface that will be implemented by the Activity, and which will establish a contract for any Activity that wants to communicate with that Fragment. For example, if you have FragmentA, which wants to communicate with any activity that includes it, then define the FragmentAInterface which will define what method can the FragmentA call for the activities that decide to use it.
  • A Fragment wants to communicate with other Fragment => This is the case where you get the most 'complicated' situation. Since you could potentially need to pass data from FragmentA to FragmentB and viceversa, that could lead us to defining 2 interfaces, FragmentAInterface which will be implemented by FragmentB and FragmentAInterface which will be implemented by FragmentA. That will start making things messy. And imagine if you have a few more Fragments on place, and even the parent activity wants to communicate with them. Well, this case is a perfect moment to establish a shared ViewModel for the activity and it's fragments. More info here https://developer.android.com/topic/libraries/architecture/viewmodel . Basically, you need to define a SharedViewModel class, that has all the data you want to share between the activity and the fragments that will be in need of communicating data among them.

The ViewModel case, makes things pretty simpler at the end, since you don't have to add extra logic that makes things dirty in the code and messy. Plus it will allow you to separate the gathering (through calls to an SQLite Database or an API) of data from the Controller (activities and fragments).


There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

You can subscribe to events in your activity and then you can post that events in your fragments etc.

Here on my blog post you can find more detail about this pattern and also an example project to show the usage.


I'm not sure I really understood what you want to do, but the suggested way to communicate between fragments is to use callbacks with the Activity, never directly between fragments. See here http://developer.android.com/training/basics/fragments/communicating.html


You can create declare a public interface with a function declaration in the fragment and implement the interface in the activity. Then you can call the function from the fragment.


Intents를 사용하여 작업을 기본 활동으로 다시 전달합니다. 주요 활동은 onNewIntent (Intent intent)를 재정 의하여이를 청취하는 것입니다. 예를 들어 주요 활동은 이러한 작업을 해당 조각으로 변환합니다.

따라서 다음과 같이 할 수 있습니다.

public class MainActivity extends Activity  {

    public static final String INTENT_ACTION_SHOW_FOO = "show_foo";
    public static final String INTENT_ACTION_SHOW_BAR = "show_bar";


   @Override
   protected void onNewIntent(Intent intent) {
        routeIntent(intent);
   }

  private void routeIntent(Intent intent) {
       String action = intent.getAction();
       if (action != null) {               
            switch (action) {
            case INTENT_ACTION_SHOW_FOO:
                // for example show the corresponding fragment
                loadFragment(FooFragment);
                break;
            case INTENT_ACTION_SHOW_BAR:
                loadFragment(BarFragment);
                break;               
        }
    }
}

그런 다음 모든 조각 내부에서 foo 조각을 표시합니다.

Intent intent = new Intent(context, MainActivity.class);
intent.setAction(INTENT_ACTION_SHOW_FOO);
// Prevent activity to be re-instantiated if it is already running.
// Instead, the onNewEvent() is triggered
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
getContext().startActivity(intent);

참조 URL : https://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices

반응형