我正在实现一个应用程序,用户可以在一个单独的选项卡中搜索一些歌曲。歌曲的搜索结果是歌词、含义等信息。从结果中,用户可以将某些歌曲标记为收藏在另一个选项卡中。当我单击最喜欢的歌曲选项卡时,它应该切换到带有搜索结果片段的第一个选项卡。以下是更具体的细节:
- 主要活动产生创建 2 个选项卡的操作栏。
- 搜索选项卡 - 单独的片段,结果 - 单独的片段
收藏夹选项卡 - 单独的片段
public class TabsListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final Activity mActivity; private final String mTag; private final Class<T> mClass; /** Constructor used each time a new tab is created. * @param activity The host Activity, used to instantiate the fragment * @param tag The identifier tag for the fragment * @param clz The fragment's Class, used to instantiate the fragment */ public TabsListener(Activity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } /* The following are each of the ActionBar.TabListener callbacks */ @SuppressLint("NewApi") public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity mFragment = Fragment.instantiate(mActivity, mClass.getName()); ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } @SuppressLint("NewApi") public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment, because another one is being attached ft.detach(mFragment); //ft.remove(mFragment); } } @SuppressLint("NewApi") public void onTabReselected(Tab tab, FragmentTransaction ft) { ft.attach(mFragment); // User selected the already selected tab. Usually do nothing. }
}
如何以编程方式为操作栏实现从一个选项卡到另一个选项卡的切换?