在我的应用程序中,我在一个活动中使用了2个片段,而且我有一个共同点 两个片段的按钮,我使用ViewPager和SectionsPagerAdapter。
此代码适用于我的LG g3 ,但在较旧的设备上,按钮侦听器在启动时处于非活动状态,而其上的文本是另一个片段。 并且在片段之间滑动一次后也能正常工作
onCreate
功能代码:`
sendButton = (Button) findViewById(R.id.send_button);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// listener on page selected - for each fragment
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
// This method will be invoked when a new page becomes selected.
@Override
public void onPageSelected(int position) {
setSendButton(position);
}
// This method will be invoked when the current page is scrolled
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
@Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
mViewPager.setCurrentItem(0);
setSendButton(0);
sendButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(sendMod == 0) {
setUnitConfigurationByte(getUnitConfigurationByte());
// setFlowSetPointByte(getFlowSetPointBytes())
writeConfiguration();
}
else
{
flowSetPointFragment.sendPPvCommand();
}
}
});
}
寻呼机类代码:
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: {
unitConfigurationFragment = new UnitConfigurationFragment();
setSendButton(0);
return unitConfigurationFragment;
}
case 1: {
flowSetPointFragment = new FlowSetPointFragment();
setSendButton(1);
return flowSetPointFragment;
}
}
return null;
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
setSendButton(0);
return "UNIT CONFIGURATION";
case 1:
setSendButton(1);
return "PULSE PER VOLUME";
}
return null;
}
}
和按钮的设置者
public void setSendButton(int fragment) {
if (fragment == 0) {
sendButton.setText("send units");
sendMod = 0;
}
if (fragment == 1) {
sendButton.setText("send pulse per volume");
sendMod = 1;
}
}
编辑: OnClick监听器:
sendButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(sendMod == 0) {
setUnitConfigurationByte(getUnitConfigurationByte());
// setFlowSetPointByte(getFlowSetPointBytes())
writeConfiguration();
}
else
{
flowSetPointFragment.sendPPvCommand();
}
}
});
谢谢你们!