我正在尝试使用 3 个带有活动的滑动选项卡。当前示例我有正确的幻灯片,但我似乎无法将我的活动用于选项卡内容。
主要活动
package com.example.tabsslide;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class MainActivity extends Activity implements OnTabChangeListener, OnPageChangeListener{
private TabHost host;
private ViewPager pager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
host = (TabHost)findViewById(android.R.id.tabhost);
pager = (ViewPager) findViewById(R.id.pager);
host.setup();
TabSpec spec = host.newTabSpec("tab1");
spec.setContent(R.id.tab1);
spec.setIndicator("First tab");
host.addTab(spec);
spec = host.newTabSpec("tab2");
spec.setContent(R.id.tab2);
spec.setIndicator("Second tab");
host.addTab(spec);
spec = host.newTabSpec("tab3");
spec.setContent(R.id.tab3);
spec.setIndicator("Third tab");
host.addTab(spec);
pager.setAdapter(new MyPagerAdapter(this));
pager.setOnPageChangeListener(this);
host.setOnTabChangedListener(this);
}
@Override
public void onTabChanged(String tabId){
int pageNumber = 0;
if(tabId.equals("tab1")){
pageNumber = 0;
} else if(tabId.equals("tab2")){
pageNumber = 1;
} else{
pageNumber = 2;
}
pager.setCurrentItem(pageNumber);
}
@Override
public void onPageSelected(int pageNumber) {
host.setCurrentTab(pageNumber);
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
}
MyPagerActivity
package com.example.tabsslide;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyPagerAdapter extends PagerAdapter {
private Context ctx;
public MyPagerAdapter(Context ctx){
this.ctx = ctx;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TextView tView = new TextView(ctx);
position++;
tView.setText("Page number: " + position);
tView.setTextColor(Color.RED);
tView.setTextSize(20);
container.addView(tView);
return tView;
}
@Override
public int getCount() {
return 3;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
我还有另一个示例,其中选项卡通过点击导航并显示每个活动屏幕。活动内容在每个选项卡上使用
TabSpec tab1 = tabHost.newTabSpec("First Tab");
tab1.setIndicator("Tab1");
tab1.setContent(new Intent(this,Tab1Activity.class));
我希望能够使用滑动选项卡示例在活动屏幕之间滑动。
提前致谢。