简体   繁体   English

findfragmentbyid在mainPctivity中在viewpager下托管3个片段时返回null

[英]findfragmentbyid returns null in mainActivity hosting 3 fragments under a viewpager

I am trying to write different functionalities for my FloatingActionButton depending on the fragment that the mainActivity is currently hosting. 我正在尝试为我的FloatingActionButton编写不同的功能,具体取决于mainActivity当前托管的片段。 Yet for for reason in my onClick() method, getSupportFragmentManager().findFragmentById() returns null . 但是在我的onClick()方法中, getSupportFragmentManager().findFragmentById()返回null

I haven't seen any examples of this question implemented with a viewpager and I am curious if there is a different approach I have to take. 我没有看到使用viewpager实现此问题的任何示例,我很好奇是否有一个不同的方法我必须采取。

 MainActivity

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.view.ViewPager;
    import android.util.Log;
    import android.view.View;


    public class MainActivity extends FragmentActivity {

    private Adapter mAdapter;
    private ViewPager mViewPager;
    private static FloatingActionButton bButton;
    private static String UID;
    private Intent intent;


    public static String getUID(){
        return UID;
    }



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

        mAdapter = new Adapter(getSupportFragmentManager());
        mViewPager = (ViewPager)findViewById(R.id.vPager);
        mViewPager.setAdapter(mAdapter);

        intent = getIntent();
        UID = intent.getStringExtra("uid");

        bButton = (FloatingActionButton)findViewById(R.id.bButton);
        bButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragContainer);

                if(fragment == null){

                    Log.e("TAG","FRAGMENT IS NULL!!");
                }
                else{
                    Log.e("TAG","FRAGMENT IS NOT NULL!!");

                }

              }

           });
      }
     }


NewsFeedFragment


    import android.os.Bundle;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.ListFragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.firebase.client.Firebase;
    import com.firebase.client.FirebaseError;
    import com.mycompany.neighbors.R;
    import com.mycompany.neighbors.SinglePost;

    import java.util.ArrayList;

    /**
     * Created by joshua on 5/25/2016.
     */
    public class NewsFeedFragment extends ListFragment implements AdapterView.OnItemClickListener{

        private ListView lv;
        private TextView tvUserName;
        private TextView tvStatus;
        private ArrayList<SinglePost> posts = new ArrayList<>();
        private static final String POSTS_PATH = "MY_PATH";
        private Firebase postsRef;
    //    private static final String FRAGMENT_POST = "post";


        public void postFragment(){
            Log.d("TAG", "Doing something else");

            PostFragment postFragment = new PostFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.fragContainer,postFragment)
                    .addToBackStack(null)
                    .commit();
        }

        @Override
        public void onViewCreated(View v, Bundle s){

            lv =  getListView();
            lv.setOnItemClickListener(this);

        }

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

        }

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

            View v = inflater.inflate(R.layout.fragment_post_feed_item,parent,false);//changed

            tvUserName = (TextView)v.findViewById(R.id.tvUN);
            tvStatus = (TextView)v.findViewById(R.id.tvStatus);

            postsRef = new Firebase(POSTS_PATH);
            postsRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
                @Override
                public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {

                    SinglePost post = dataSnapshot.getValue(SinglePost.class);
                    post.setKey(dataSnapshot.getKey());
                    posts.add(0, post);

                    if(posts.size() > 0) {
                        PostAdapter adapter = new PostAdapter(posts);
                        setListAdapter(adapter);
                    }else{
                        Toast toast = Toast.makeText(getActivity(),"No data", Toast.LENGTH_SHORT);
                        toast.show();
                    }

                }

                @Override
                public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });


            return v;
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id){

            SinglePost p = ((PostAdapter) getListAdapter()).getItem(position);

        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        }

        private class PostAdapter extends ArrayAdapter<SinglePost>{

           public PostAdapter(ArrayList<SinglePost> singlePost){
               super(getActivity(),android.R.layout.simple_list_item_1,singlePost);
           }

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

                if(convertView == null){
                    convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_post_feed_item,null);

                }

                SinglePost p = getItem(position);

                TextView tvUserName = (TextView)convertView.findViewById(R.id.tvUN);
                tvUserName.setText(p.getUserName());

                TextView tvStatus = (TextView)convertView.findViewById(R.id.tvStatus);
                tvStatus.setText(p.getStatus());



                return convertView;
            }

        }
    }

I have 2 other fragments but i'll post one as an example. Here is my adapter for the viewpager.

Adapter

    import android.support.v4.app.Fragment;

    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;

    import com.mycompany.neighbors.Fragments.MapFragment;
    import com.mycompany.neighbors.Fragments.NewsFeedFragment;
    import com.mycompany.neighbors.Fragments.ProfileFragment;

    /**
     * Created by joshua on 5/25/2016.
     */
    public class Adapter extends FragmentPagerAdapter {


            private String Fragment[] = {"Posts" , "Map" , "Profile"};
            public Adapter(FragmentManager fm){
                super (fm);
            }


            @Override
            public Fragment getItem(int position) {
                switch(position){
                    case 0:
                        return new NewsFeedFragment();
                    case 1:
                        return new MapFragment();
                    case 2:
                        return new ProfileFragment();

                    default:
                        return null;
                }

            }

            @Override
            public int getCount(){return Fragment.length;}

            @Override
            public CharSequence getPageTitle(int position) {
                return Fragment[position];
            }

        }

Please check below link, It has very good explanation for your problem: 请查看以下链接,它对您的问题有很好的解释:

http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html

Or you can try below code snippet: 或者你可以尝试下面的代码片段:

1.Where you add fragment in view pager or view pager adapter: 1.在视图寻呼机或视图寻呼机适配器中添加片段的位置:

MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment,"Some Tag").commit();

2.To get the tag for the currently visible page, you then call: 2.要获取当前可见页面的标记,请调用:

int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);

3.and then get the fragment page: 3.然后获取片段页面:

Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM