Android Fragment应用实战(音乐播放器界面)

来源:互联网 发布:网络快车下载 编辑:程序博客网 时间:2024/05/29 17:11

当下很多手机应用都会有一个非常类似的功能,即屏幕的下方显示一行Tab标签选项,点击不同的标签就可以切换到不同的界面,如以下几个应用所示:


以上底部这四个标签,每一个分别对应一个Fragment,这种底部标签式的布局策略真的非常常见,那么话说回来,这种效果到底是如何的呢?熟悉Android的朋友一定都会知道,很简单嘛,使用TabHost就OK了!但是殊不知,TabHost并非是那么的简单,它的可扩展性非常的差,不能随意地定制Tab项显示的内容,而且运行还要依赖于ActivityGroup。ActivityGroup原本主要是用于为每一个TabHost的子项管理一个单独的Activity,但目前已经被废弃了。为什么呢?当然就是因为Fragment的出现了!

下面就开始真正的编程吧!

打开或者新建一个xml文件作为程序的主布局文件,这里直接采用activity_main.xml作为程序的主布局文件,在里面加入如下代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <FrameLayout        android:id="@+id/Content"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" >        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="match_parent"            android:background="#eee" >                        <android.support.v4.view.ViewPager                android:id="@+id/discover_music_view_pager"                android:layout_width="match_parent"                android:layout_height="match_parent" />        </RelativeLayout>    </FrameLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="60dp"        android:background="#ffffff" >                <RelativeLayout            android:id="@+id/discover_layout"            android:layout_width="0dp"            android:layout_height="match_parent"            android:layout_weight="1" >                        <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_centerVertical="true"                android:orientation="vertical" >                <ImageView                    android:id="@+id/discover_image"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:src="@drawable/ic_launcher" />                <TextView                    android:id="@+id/discover_text"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:text="发现音乐"                    android:textColor="#82858b" />            </LinearLayout>        </RelativeLayout>        <RelativeLayout            android:id="@+id/my_layout"            android:layout_width="0dp"            android:layout_height="match_parent"            android:layout_weight="1" >            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_centerVertical="true"                android:orientation="vertical" >                <ImageView                    android:id="@+id/my_image"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:src="@drawable/ic_launcher" />                <TextView                    android:id="@+id/my_text"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:text="我的音乐"                    android:textColor="#82858b" />            </LinearLayout>        </RelativeLayout>        <RelativeLayout            android:id="@+id/friends_layout"            android:layout_width="0dp"            android:layout_height="match_parent"            android:layout_weight="1" >            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_centerVertical="true"                android:orientation="vertical" >                <ImageView                    android:id="@+id/friends_image"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:src="@drawable/ic_launcher" />                <TextView                    android:id="@+id/friends_text"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:text="朋友"                    android:textColor="#82858b" />            </LinearLayout>        </RelativeLayout>        <RelativeLayout            android:id="@+id/account_layout"            android:layout_width="0dp"            android:layout_height="match_parent"            android:layout_weight="1" >            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_centerVertical="true"                android:orientation="vertical" >                <ImageView                    android:id="@+id/account_image"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:src="@drawable/ic_launcher" />                <TextView                    android:id="@+id/account_text"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:text="账号"                    android:textColor="#82858b" />            </LinearLayout>        </RelativeLayout>    </LinearLayout></LinearLayout>

大家看这代码比较难以理解,但其实主要就分为两部分。第一个部分就是FrameLayout,这里只是给FrameLayout的id设置为Content,并没有在里面添加任何具体的内容,因为具体的内容是要在后面动态进行添加的。第二个部分就是FrameLayout下面的LinearLayout,这个LinearLayout中包含的就是整个类似于TabHost的布局。可以看到,我们将这个LinearLayout又等分成了四份,每一份中都会显示一个ImageView和一个TextView。ImageView用于显示当前Tab的图标,TextView用于显示当前Tab的标题,这个效果就会和QQ非常得类似。


那么接下来我们要开始实现Fragment和它们的布局了,新建一个discover_music_fragment.xml作为第一个“发现音乐”的界面,代码如下所示:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:orientation="vertical" >        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center_horizontal"            android:src="@drawable/ic_launcher" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center_horizontal"            android:padding="10dp"            android:text="这是发现音乐界面"            android:textSize="20sp" />    </LinearLayout></RelativeLayout>

这个布局就是在屏幕的正中央显示一个消息图标以及一段文字。


然后,我们要去创建对应这个布局的Fragment,新建一个DiscoverMusicFragment继承自Fragment,代码如下所示

public class DiscoverMusicFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View discover_music_fragment = inflater.inflate(R.layout.discover_music_fragment, container, false);return discover_music_fragment;}}

后面的都和这个一样,就不一一展示。

这样我们把每一个Fragment以及它们对应的布局文件都创建好了,接下来我们开始写MainActivity里面的内容,代码如下所示:

public class MainActivity extends Activity implements OnClickListener {/** * 用于展示‘发现音乐’的Fragment */private DiscoverMusicFragment discoverMusicFragment;/** * 用于展示‘我的音乐’的Fragment */private MyMusicFragment myMusicFragment;/** * 用于展示‘朋友’的Fragment */private FriendsFragment friendsFragment;/** * 用于展示‘账号’的Fragment */private AccountFragment accountFragment;/** * ‘发现音乐’布局 */private View discover_music_layout;/** * ‘我的音乐’布局 */private View my_music_layout;/** * ‘朋友’布局 */private View friends_layout;/** * ‘账号’布局 */private View account_layout;/** * 在Tab布局上显示‘发现音乐’图标的控件 */private ImageView discover_music_image;/** * 在Tab布局上显示‘我的音乐’图标的控件 */private ImageView my_music_image;/** * 在Tab布局上显示‘朋友’图标的控件 */private ImageView friends_image;/** * 在Tab布局上显示‘账号’图标的控件 */private ImageView account_image;/** * 在Tab布局上显示‘发现音乐’标题的控件 */private TextView discover_music_text;/** * 在Tab布局上显示‘我的音乐’标题的控件 */private TextView my_music_text;/** * 在Tab布局上显示‘朋友’标题的控件 */private TextView friends_text;/** * 在Tab布局上显示‘账号’标题的控件 */private TextView account_text;/** * 用于对Fragment进行管理 */private FragmentManager fragmentManager;/** * ‘我的音乐’界面‘下载音乐’ */@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);// 初始化布局元素initViews();fragmentManager = getFragmentManager();// 第一次启动时选中第0个tabsetTabSelection(0);}private void initViews() {// 四个布局discover_music_layout = findViewById(R.id.discover_layout);my_music_layout = findViewById(R.id.my_layout);friends_layout = findViewById(R.id.friends_layout);account_layout = findViewById(R.id.account_layout);// 四个图片discover_music_image = (ImageView) findViewById(R.id.discover_image);my_music_image = (ImageView) findViewById(R.id.my_image);friends_image = (ImageView) findViewById(R.id.friends_image);account_image = (ImageView) findViewById(R.id.account_image);// 四个标题discover_music_text = (TextView) findViewById(R.id.discover_text);my_music_text = (TextView) findViewById(R.id.my_text);friends_text = (TextView) findViewById(R.id.friends_text);account_text = (TextView) findViewById(R.id.account_text);// 设置监听事件discover_music_layout.setOnClickListener(this);my_music_layout.setOnClickListener(this);friends_layout.setOnClickListener(this);account_layout.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.discover_layout:// 当点击了‘发现音乐’tab时,选中第1个tabsetTabSelection(0);break;case R.id.my_layout:// 当点击了‘我的音乐’tab时,选中第2个tabsetTabSelection(1);break;case R.id.friends_layout:// 当点击了‘朋友’tab时,选中第3个tabsetTabSelection(2);break;case R.id.account_layout:// 当点击了‘账号’tab时,选中第4个tabsetTabSelection(3);break;default:break;}}/** * 根据传入的index参数来设置选中的tab页。 *  * @param index *            每个tab页对应的下标。0表示发现音乐,1表示我的音乐,2表示朋友,3表示账号。 */private void setTabSelection(int index) {// 每次选中之前要清除掉上次选中的状态clearSelection();// 开启一个Fragment事务FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// 先隐藏掉所有的Fragment,以防止有多个Fragment显示在界面上的情况HideFragments(fragmentTransaction);switch (index) {case 0:// 当点击了‘发现音乐’时,改变文字的颜色discover_music_text.setTextColor(Color.BLUE);if (discoverMusicFragment == null) {// 如果discoverMusicFragment为空,则创建一个并添加到界面上discoverMusicFragment = new DiscoverMusicFragment();fragmentTransaction.add(R.id.Content, discoverMusicFragment);} else {// 如果discoverMusicFragment不为空,则将其显示出来fragmentTransaction.show(discoverMusicFragment);}break;case 1:// 当点击了‘我的音乐’时,改变文字的颜色my_music_text.setTextColor(Color.BLUE);if (myMusicFragment == null) {// 如果myMusicFragment为空,则创建一个并添加到界面上myMusicFragment = new MyMusicFragment();fragmentTransaction.add(R.id.Content, myMusicFragment);} else {// 如果myMusicFragment不为空,则将其显示出来fragmentTransaction.show(myMusicFragment);}break;case 2:// 当点击了‘朋友’时,改变文字的颜色friends_text.setTextColor(Color.BLUE);if (friendsFragment == null) {// 如果friendsFragment为空,则创建一个并添加到界面上friendsFragment = new FriendsFragment();fragmentTransaction.add(R.id.Content, friendsFragment);} else {// 如果friendsFragment不为空,则将其显示出来fragmentTransaction.show(friendsFragment);}break;case 3:// 当点击了‘账号’时,改变文字的颜色account_text.setTextColor(Color.BLUE);if (accountFragment == null) {// 如果accountFragment为空,则创建一个并添加到界面上accountFragment = new AccountFragment();fragmentTransaction.add(R.id.Content, accountFragment);} else {// 如果accountFragment不为空,则将其显示出来fragmentTransaction.show(accountFragment);}break;default:break;}fragmentTransaction.commit();}/** * 将所有的Fragment都设置为隐藏状态 *  * @param fragmentTransaction *            用于对Fragment执行操作的事务 */private void HideFragments(FragmentTransaction fragmentTransaction) {if (discoverMusicFragment != null) {fragmentTransaction.hide(discoverMusicFragment);}if (myMusicFragment != null) {fragmentTransaction.hide(myMusicFragment);}if (friendsFragment != null) {fragmentTransaction.hide(friendsFragment);}if (accountFragment != null) {fragmentTransaction.hide(accountFragment);}}/** * 清除掉所有选中状态 */private void clearSelection() {discover_music_text.setTextColor(Color.parseColor("#82858b"));my_music_text.setTextColor(Color.parseColor("#82858b"));friends_text.setTextColor(Color.parseColor("#82858b"));account_text.setTextColor(Color.parseColor("#82858b"));}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

代码看不懂的大家可以参照上面的注释。

下面我再带大家简单梳理一遍。在onCreate()方法中先是调用了initViews()来获取每个控件的实例,并给相应的控件设置好点击事件,然后调用setTabSelection()方法设置默认的选中项,这里传入的0说明默认选中第1个Tab项。

那么setTabSelection()方法中又是如何处理的呢?可以看到,首先第一步是调用clearSelection()方法来清理掉之前的选中状态,然后开启一个Fragment事务,并隐藏掉所有的Fragment,以防止有多个Fragment显示在界面上。接下来根据传入的index参数判断出选中的是哪一个Tab项,并改变该Tab项的图标和文字颜色,然后将相应的Fragment添加到界面上。这里注意一个细节,我们添加Fragment的时候并没有使用replace()方法,而是会先判断一下该Fragment是否为空,如果是空的则调用add()方法添加一个进来,如果不是空的则直接调用show()方法显示出来即可。那么为什么没有使用replace()方法呢?这是因为replace()方法会将被替换掉的那个Fragment彻底地移除掉,该Fragment的生命周期就结束了。当再次点击刚才那个Tab项的时候,就会让该Fragment的生命周期重新开始,onCreate()、onCreateView()等方法都会重新执行一遍。这显然不是我们想要的,也和ActivityGroup的工作原理不符,因此最好的解决方案就是使用hide()和show()方法来隐藏和显示Fragment,这就不会让Fragment的生命周期重走一遍了。

设置完默认选中项后,我们当然还可以通过点击Tab项来自由地切换界面,这就会进入到onClick()方法中。onClick()方法中的逻辑判断非常简单,当点击了消息标签时就会选中第1个tab项,点击联系人标签时就会选中第2个tab项,点击动态标签时就会选中第3个tab项,点击设置标签时就会选中第4个tab项。都是通过调用setTabSelection()方法来完成的,只是传入了不同的参数。

好了,这样我们就将全部的代码都编写完成了。

大家赶紧去试一下吧!

还有一点,这个效果在横屏的时候也可以的哦!

好了,今天的讲解到此结束,有疑问的朋友请在下面留言!谢谢!


2 0