Tab3代码开始工作而不使用tab选择它。当我启动MainActivity时,所有选项卡代码同时工作。当用户选择选项卡时,我是如何使它们工作的 我猜onCreateView是错误的。我试图使用其他方法,但所有这些方法都在切换到制表符之前触发。 感谢
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting.");
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new tab1_fragment(), "TAB1");
adapter.addFragment(new tab2_fragment(), "TAB2");
adapter.addFragment(new tab3_fragment(), "TAB3");
viewPager.setAdapter(adapter);
}
}
SectionsPageAdapter.java
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
}
TAB3:
public class tab3_fragment extends Fragment {
private static final String TAG = "Tab3Fragment";
private Button btnTEST;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab3_fragment,container,false);
btnTEST = (Button) view.findViewById(R.id.btnTEST3);
btnTEST.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 3",Toast.LENGTH_SHORT).show();
}
});
//This is called when i launch mainactivty as intent but i want to make this work when user selects tab 3
Toast.makeText(getActivity(), "tab 3 selected",Toast.LENGTH_SHORT).show();
return view;
}
}
答案 0 :(得分:2)
覆盖片段中的setUserVisibleHint(),此方法仅在片段对用户可见时才会调用。
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if(isVisibleToUser)
{
Toast.makeText(getActivity(), "tab 3 selected",Toast.LENGTH_SHORT).show();
}
}