如何在片段中实现监听器接口?

时间:2014-03-06 00:36:32

标签: java android android-fragments

我正在尝试在活动和位于其上的片段之间进行通信,我希望每次发生onclick时都会将新数据(从数据库中检索的图像/文本)传递到frag中(onclick在活动)。我做了一个简单的界面来测试(让我知道这是不适合图像,或者它是否太慢或效率低),我试图让它包含在我的片段中,所以当一个onclick发生时,片段会改变图像和文本。

这是简单的界面代码:

public interface FragmentCommunicator {
    public void passDataToFragment(String someValue);
}

以下是活动代码:

public class RandomActivity extends FragmentActivity implements ActivityCommunicator {

    //viewpager adapter
    private PageAdapter mAdapter;
    private ViewPager viewPager;

    //interface through which communication is made to fragment
    public FragmentCommunicator fragmentCommunicator;

    //Buttons for yes, no, skip
    Button btnYesRandom, btnNoRandom, btnSkipRandom;

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

        //set buttons
        btnYesRandom = (Button) findViewById(R.id.btnYesRandom);

        // Initializing pager
        viewPager = (ViewPager) findViewById(R.id.random_pager);

        //calling bundle to attach data to fragment
        Bundle bundle = new Bundle();
        bundle.putString("edttext", "From Activity");

        // set Fragmentclass Arguments
        RandomFragment randFrag = new  RandomFragment();
        randFrag.setArguments(bundle);

        //Setting up fragment
        FragmentManager fm = getFragmentManager();
        mAdapter = new PageAdapter(getSupportFragmentManager(),  new UserUpVotesFragment(), randFrag, new UserDownVotesFragment());
        viewPager.setAdapter(mAdapter);
        // Here you would declare which page to visit on creation
        viewPager.setCurrentItem(1);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {}
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            public void onPageSelected(int position) {
                // Check if this is the page you want.
                if(position !=1) {
                    //swiping to the right
                    if(position == 0) {
                        Log.e("Swiping", "SWIPING TO THE Right BUT RESET ERR");
                        getIntent().removeExtra("edttext");
                    }

                    //swiping to the left
                    if(position == 2) {
                        Log.e("Swiping", "SWIPING TO THE left BUT RESET ERR");
                    }

                    // RandomFragment randomFrag = (RandomFragment) getFragmentManager().findFragmentById(R.id.fra);

                    viewPager.setCurrentItem(1);
                }
            }
        });

        btnYesRandom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                if(fragmentCommunicator != null)
                    fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
            }
        });
    }

片段代码:

public class RandomFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //call data from activity bundle
        String strtext = getArguments().getString("edttext");

        View rootView = inflater.inflate(R.layout.fragment_random, container, false);

        RelativeLayout random_frag_layout = (RelativeLayout) rootView.findViewById(R.id.random_frag_layout);

        activityButton = (ImageView) rootView.findViewById(R.id.imagehere);
        //setRetainInstance(true);

        texthere = (TextView) rootView.findViewById(R.id.texthere);
        texthere.setText(strtext);

        return rootView;
    }

    //FragmentCommunicator interface implementation
    public void passDataToFragment(String someValue){
        activityAssignedValue = someValue;
        Log.e("ACTIVITY", activityAssignedValue);
    }
}

2 个答案:

答案 0 :(得分:4)

如果您只有一个片段,则可以直接访问它并仅通过方法发送任何数据:将您的片段设为一个字段,然后通过活动调用您的passDataToFragment()

要从片段访问活动,请致电((RandomActivity)getActivity()).activityMethod()

答案 1 :(得分:0)

什么是ActivityCommunicator

如果你希望沿着这条路走下去,你的RandomActivity类会实现FragmentCommunicator接口,该接口应该被声明为RandomFragment类中的内部公共接口,或者公开(或打包本地)在自己的文件中。