7

setText 関数を使用して EditText テキストを変更するメソッド setName() を持つ Fragment があります。

ViewPager を使用してそのフラグメントをホストするアクティビティからそのメソッドを呼び出す最良の方法は何ですか?

つまり、ViewPager を使用してそのフラグメントをホストする Activity から Fragment のメソッド (たとえば、そのフラグメントのレイアウトを変更する) にアクセスするにはどうすればよいでしょうか?

いくつかの方法を試しましたが、常にエラーが発生したため、これを求めています。

4

4 に答える 4

12

Best way to do this, just call

CallingFragmentName fragment = (CallingFragmentName) viewPager
                    .getAdapter()
                    .instantiateItem(viewPager, viewPager.getCurrentItem());

It will re-instantiate your calling Fragment, so that it will not throw null pointer exception.

于 2018-08-23T10:24:28.417 に答える
7

これが少し遅れていることは知っていますが、同じ問題に遭遇しました。すでに解決していれば、他の人に役立つかもしれません。

ViewPager で最初に発見した問題は、フラグメントへの参照を取得することがほとんど不可能だということです。フラグメントは getItem() で動的に作成されるため、ID を設定することはできず、スイッチャーによって自動的に再タグ付けされるため、タグで見つけることもできません。いくつかの方法がありますが、すべて回避策です。( ViewPager の一部として ListFragment のデータを更新します)

私がそれを解決した方法は、本質的に二重のコールバックを使用することでした。フラグメント A にはメイン アクティビティによって実装されたインターフェイスがあり、メイン アクティビティにはフラグメント B によって実装されたインターフェイスがあります。たとえば、フラグメント A でボタンがクリックされると、メイン アクティビティのコールバック関数が呼び出され、次にフラグメント B のコールバックが呼び出されます。以下のコードを見てください。私はすべてを投稿したことを願っています。ところで、私はこれを ViewPager でのみ試しましたが、あらゆる種類の Fragment 通信で機能すると思います。

主なアクティビティ Java:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity implements FragmentA.Caller {

    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;
    PassCallToB passOnToB = null;
    FragmentManager myManager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            MyManager = fm;
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            if(position == 0) {
                fragment = new FragmentA();
            } else if (position == 1) {
                fragment = new FragmentB();
                passOnToB = (PassCallToB)fragment;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return "Frag A";
            case 1:
                return "Frag B";
            }
            return null;
        }

        public void setCallback() {
            List<Fragment> frags = myManager.getFragments();
            for(Fragment fragment : frags) {
                if(fragment instanceof FragmentB){
                    passOnToB = (PassCallToB)fragment;
                }
            }
        }
    }

    public interface PassCallToB {
        public void passItOn();
    }

    @Override
    public void CallB() {
        if(passOnToB instanceof Fragment)
            passOnToB.passItOn();
        else {
            mSectionsPagerAdapter.setCallback();
            passOnToB.passItOn();
        }
    }
}

メイン アクティビティ xml:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <android.support.v4.view.PagerTitleStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:paddingBottom="4dp"
        android:paddingTop="4dp"
        android:textColor="#fff" />

</android.support.v4.view.ViewPager>

フラグメント A java:

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentA extends Fragment {

    Button btnCallB = null;

    Caller listener = null;

    public FragmentA() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
        View rootView = inflater.inflate(R.layout.fragment_a, container, false);

        btnCallB = (Button)rootView.findViewById(R.id.btnCallB);
        btnCallB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                listener.CallB();
            }

        });

        return rootView;
    }

    public interface Caller {
        public void CallB();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof FragmentActivity) {
          listener = (Caller) activity;
        } else {
          throw new ClassCastException(activity.toString() + " must implemenet listener");
        }
    }

     @Override
      public void onDetach() {
        super.onDetach();
        listener = null;
      }
}

フラグメント A xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="This is Fragment A" />

    <Button
        android:id="@+id/btnCallB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:text="Call Fragment B" />

</RelativeLayout>

フラグメント B Java:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class FragmentB extends Fragment implements MainActivity.PassCallToB {

    public FragmentB() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
        View rootView = inflater.inflate(R.layout.fragment_b, container, false);
        return rootView;
    }

    @Override
    public void passItOn() {
        Toast.makeText(getActivity(), "Hello from B", Toast.LENGTH_SHORT).show();

    }
}

フラグメント B xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="This is Fragment B" />

</RelativeLayout>
于 2013-09-27T18:34:28.903 に答える