我从高处和低处寻找答案。那里有一些很棒的资源,但我发现目前没有一个可以合并到我的代码中。但是,我是 java/android 编程的初学者,也就是菜鸟,所以这可能是问题哈哈。我有以下工作代码。每个选项卡都有一个与之关联的类。四个选项卡,四个类以及与每个选项卡/类一起使用的 xml。我在这段代码中实现了动作栏,片段。我想实现水平滑动动作。我还希望能够单击选项卡以及在它们之间滑动。有人可以帮我在现有代码中完成这项工作吗?帮我找个好教程?让我知道是否可以更正或改进我当前的代码以实现这一点?如果您需要更多信息,请告诉我。这是代码提前谢谢!
MainActivity.java
public class MainActivity extends Activity {
private static final String TAB_KEY_INDEX = "tab_key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab mActivityATab = actionbar.newTab().setText(
getString(R.string.ui_tabname_a));
ActionBar.Tab mActivityBTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_b));
ActionBar.Tab mActivityCTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_c));
ActionBar.Tab mActivityDTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_d));
Fragment mActivityA = new ActivityA();
Fragment mActivityB = new ActivityB();
Fragment mActivityC = new ActivityC();
Fragment mActivityD = new ActivityD();
mActivityATab.setTabListener(new MyTabsListener(mActivityA,
getApplicationContext()));
mActivityBTab.setTabListener(new MyTabsListener(mActivityB,
getApplicationContext()));
mActivityCTab.setTabListener(new MyTabsListener(mActivityC,
getApplicationContext()));
mActivityDTab.setTabListener(new MyTabsListener(mActivityD,
getApplicationContext()));
actionbar.addTab(mActivityATab);
actionbar.addTab(mActivityBTab);
actionbar.addTab(mActivityCTab);
actionbar.addTab(mActivityDTab);
if (savedInstanceState != null) {
actionbar.setSelectedNavigationItem(savedInstanceState.getInt(
TAB_KEY_INDEX, 0));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem_quit:
finish();
return true;
}
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(TAB_KEY_INDEX, getActionBar()
.getSelectedNavigationIndex());
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public MyTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
}
活动A(其余类同)
public class ActivityA extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activitya, container, false);
}}