我用 Sherlock Fragment 创建了一个类,以使用 ViewPager 启用 Swipe 视图。现在我正在尝试使用 setBackgroundResource() 方法更改 tabspec 中可能的选项卡背景,但它不起作用。我想为每个选项卡添加自定义背景,同时关注/选择/未选择它。
我尝试使用选择器,但没有用
<item android:drawable="@drawable/selected" android:state_selected="true"/>
<item android:drawable="@drawable/not_selected" android:state_selected="false"/>
mActionBar.setStackedBackgroundDrawable(getResources().getDrawable(
R.drawable.tab_indicator));
这是我的主要课程
public class MainActivity extends SherlockFragmentActivity {
// Declare Variables
ActionBar mActionBar;
ViewPager mPager;
Tab tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Activate Navigation Mode Tabs
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// Activate Fragment Manager
FragmentManager fm = getSupportFragmentManager();
// Capture ViewPager page swipes
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// Find the ViewPager Position
mActionBar.setSelectedNavigationItem(position);
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
// Locate the adapter class called ViewPagerAdapter.java
ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
// Set the View Pager Adapter into ViewPager
mPager.setAdapter(viewpageradapter);
// Capture tab button clicks
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Create first Tab
tab = mActionBar.newTab().setText("Tab1").setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setText("Tab2").setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setText("Tab3").setTabListener(tabListener);
mActionBar.addTab(tab);
}
}