Я знаю, что здесь много подобных вопросов, но ни один из них пока не помог мне, поэтому я надеюсь, что, просто разместив здесь свой (слегка отредактированный) класс, кто-то может мне помочь. Это ViewPager, использующий 4 фрагмента в качестве страниц.
Итак, моя проблема в том, что метод getFragmentByPosition не работает, потому что getSupportFragmentManager() возвращает значение null. В моем onCreate mSectionsPagerAdapter также возвращает null, если я пытаюсь вызвать что-либо из этого, однако все мои вкладки отображаются нормально, и я просто не могу получить доступ к данным из своих фрагментов, которые мне нужны.
Я действительно не знаю, в чем проблема на данный момент, поэтому любая помощь приветствуется. Я отправил несколько других вопросов раньше и попробовал предложения безрезультатно, так что теперь я просто публикую весь свой класс. Спасибо!
package com.me.testapp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import com.me.testapp.CheckListFragments.Thing1Fragment;
import com.me.testapp.CheckListFragments.Thing2Fragment;
import com.me.testapp.CheckListFragments.Thing3Fragment;
import com.me.testapp.CheckListFragments.Thing4Fragment;
import com.me.testapp.Data.ClientDAO;
import io.karim.MaterialTabs;
public class CheckList extends AppCompatActivity
implements Thing1Fragment.OnFragmentInteractionListener,
Thing2Fragment.OnFragmentInteractionListener,
Thing3Fragment.OnFragmentInteractionListener,
Thing4Fragment.OnFragmentInteractionListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
/**
* The {@link ViewPager} that will host the section contents.
*/
public SectionsPagerAdapter mSectionsPagerAdapter;
public ViewPager pager;
private ClientDAO clientDAO;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView toolbarName = (TextView) findViewById(R.id.toolbar_name);
TextView toolbarFloor = (TextView) findViewById(R.id.toolbar_floor);
TextView toolbarOffice = (TextView) findViewById(R.id.toolbar_office);
toolbarName.setText(getIntent().getStringExtra("Name"));
toolbarRoom.setText(": " + getIntent().getStringExtra("Office"));
toolbarFloor.setVisibility(View.GONE);
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
mSectionsPagerAdapter = new SectionsPagerAdapter(this.getSupportFragmentManager());
pager.setAdapter(mSectionsPagerAdapter);
pager.setOffscreenPageLimit(3);
// Bind the tabs to the ViewPager
MaterialTabs tabs = (MaterialTabs) findViewById(R.id.tabs);
tabs.setViewPager(pager);
clientDAO = new ClientDAO(getApplicationContext());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_checklist, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch(position) {
case 0:
Thing1Fragment thing1 = new Thing1Fragment();
return thing1;
case 1:
Thing2Fragment thing2 = new Thing2Fragment();
return thing2;
case 2:
Thing3Fragment thing3 = new Thing3Fragment();
return thing3;
case 3:
Thing4Fragment thing4 = new Thing4Fragment();
return thing4;
default:
thing1 = new Thing1Fragment();
return thing1;
}
}
@Override
public int getCount() {
// Show 4 total pages.
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
public void onFragmentInteraction(Uri uri){
//you can leave it empty
}
public int booleanToInt(boolean bool) {
return bool ? 1 : 0;
}
public Fragment getFragmentByPosition(int pos) {
String tag = "android:switcher:" + R.id.pager + ":" + pos;
return getSupportFragmentManager().findFragmentByTag(tag);
}
public int getCheckboxState(int id, String page) {
switch (page) {
case "thing1":
return booleanToInt(((CheckBox) getFragmentByPosition(0).getView().findViewById(id)).isChecked());
case "thing2":
return booleanToInt(((CheckBox) getFragmentByPosition(1).getView().findViewById(id)).isChecked());
case "thing3":
return booleanToInt(((CheckBox) getFragmentByPosition(2).getView().findViewById(id)).isChecked());
case "thing4":
return booleanToInt(((CheckBox) getFragmentByPosition(3).getView().findViewById(id)).isChecked());
default:
return booleanToInt(((CheckBox) getFragmentByPosition(0).getView().findViewById(id)).isChecked());
}
}
}