简体   繁体   中英

How to call a tabbed activity fragment from main activity?

I have selected a tabbed activity template with "Action bar tabs" in android studio.

Then i had created three fragments (One.java, Two.java, Three.java) one for each of the tabs.

I have the code related to the cursors in the second fragment.The thing is when i run the application the code in the second fragment is not being executed.

My question is will the fragment (Two.java) will be called implicitly or it is needed to call by creating an instance (if yes, how?).

code snippet for MainActivity.java

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

       if(getArguments().getInt(ARG_SECTION_NUMBER)==1){
            View rootView = inflater.inflate(R.layout.fragment_one, container, false);

            return rootView;
        }
        else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
           View rootView = inflater.inflate(R.layout.fragment_two, container, false);
               return rootView;

           } else {
               View rootView = inflater.inflate(R.layout.fragment_three, container, false);
               return rootView;
           }
    }

code snippet for Two.java

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    logReader1 = new LogReader(getContext());
    db = logReader1.getReadableDatabase();
    Cursor logCursor = db.rawQuery("SELECT rowid _id,name,Time_Used,app_Image FROM logs ORDER BY Time_Used DESC", null);
    LogCursorAdapter logAdapter = new LogCursorAdapter((MainActivity) getContext(), logCursor);
    ListView log_Items = (ListView) container.findViewById(R.id.list_item);
    log_Items.setAdapter((logAdapter));
    return log_Items;

}

From what I can tell you aren't actually creating a new fragment. You're inflating the layout that you're intending to use as the layout for the fragment two.

Something like https://developer.android.com/training/implementing-navigation/lateral.html should get you pointed in the right direction. Notice how they create and return a fragment in the DemoCollectionPagerAdapter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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