android基础---ViewPager与fragment

这篇博客探讨了如何使用ViewPager和Fragment来实现类似微信主界面的应用布局。主要内容包括创建top.xml和bottom.xml布局文件,底部用LinearLayout实现选项卡,通过包括在main.xml中并用ViewPager或Fragment进行动态内容展示。还提到了点击事件处理和Fragment的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在日常开发中,ViewPager和Fragment随处可见,例如微信的主界面可以用它们来实现。


分析一下微信主界面:头部是一个TextView。底部是一个选项卡。重点就在中间部分。我们今天也主要学习中间部分的实现。

以下将会用类似于微信的一个App布局来举例

(一)

首先我们先建立两个布局文件:top.xml和bottom.xml分别实现顶部是底部    (top.xml为一个TextView就不多说了。bottom.xml底部是4个选项卡,分别是:新闻、朋友、抢钱、我。这个有很多种实现方法,我们今天用最简单的一种:LineaLayout.。即一个大的线性布局里包含着4个LinearLayout)

以下为bottom.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="#D6D7D7">
    <LinearLayout
        android:id="@+id/ll_news"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:gravity="center">
        <ImageButton
            android:id="@+id/img_news"
            android:layout_width="wrap_content"
            android:clickable="false"
            android:layout_height="wrap_content"
            android:src="@drawable/tab_icon_news_light"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="新闻"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/ll_friend"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:gravity="center">
        <ImageButton
            android:id="@+id/img_friend"
            android:layout_width="wrap_content"
            android:clickable="false"
            android:layout_height="wrap_content"
            android:src="@drawable/tab_icon_friend_dark"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="并友"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_money"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:gravity="center">
        <ImageButton
            android:id="@+id/img_money"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="false"
            android:src="@drawable/tab_icon_money_dark"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="抢钱"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_me"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:gravity="center">
        <ImageButton
            android:id="@+id/img_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="false"
            android:src="@drawable/tab_icon_me_dark"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我"/>
    </LinearLayout>


</LinearLayout>


(二)

建立四个布局备用,将会绑定为底部的控制的相应布局:这里的四个xml为:news.xml   friend.xml   money.xml    me.xml

举例一个(其他三个类似):

news.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is the news tab"
        android:textSize="35sp"/>

</LinearLayout>


(二)

建立main.xml作为主布局文件:把以上建立的两个xml用include标签包含进来。在两个include标签之间,用什么实现呢?主要有两种方法:

1、用ViewPager

建立mainActivity,加载main。xml。在mainActivity中,

package com.lm2.newsapp;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class index extends AppCompatActivity implements View.OnClickListener{
    private ViewPager view_pager;
    private LinearLayout ll_news,ll_friend,ll_money,ll_me;
    private ImageButton img_news,img_friend,img_money,img_me;
    private PagerAdapter adapter;
    private List<View> list=new ArrayList<View>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        initView();
        initEvent();
    }

    private void initEvent() {
        ll_news.setOnClickListener(this);
        ll_friend.setOnClickListener(this);
        ll_money.setOnClickListener(this);
        ll_me.setOnClickListener(this);
        view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int i=view_pager.getCurrentItem();
                resetImg();
                switch (i){
                    case 0:
                        img_news.setImageResource(R.drawable.tab_icon_news_light);
                        break;
                    case 1:
                        img_friend.setImageResource(R.drawable.tab_icon_friend_light);
                        break;
                    case 2:
                        img_money.setImageResource(R.drawable.tab_icon_money_light);
                        break;
                    case 3:
                        img_me.setImageResource(R.drawable.tab_icon_me_light);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    public void initView(){
        view_pager=(ViewPager)findViewById(R.id.view_pager);
        ll_news=(LinearLayout)findViewById(R.id.ll_news);
        ll_friend=(LinearLayout)findViewById(R.id.ll_friend);
        ll_money=(LinearLayout)findViewById(R.id.ll_money);
        ll_me=(LinearLayout)findViewById(R.id.ll_me);
        img_news=(ImageButton)findViewById(R.id.img_news);
        img_friend=(ImageButton)findViewById(R.id.img_friend);
        img_money=(ImageButton)findViewById(R.id.img_money);
        img_me=(ImageButton)findViewById(R.id.img_me);

        LayoutInflater inflater=LayoutInflater.from(this);
        View vnews=inflater.inflate(R.layout.news,null);
        View vfriend=inflater.inflate(R.layout.friend,null);
        View vmoney=inflater.inflate(R.layout.money,null);
        View vme=inflater.inflate(R.layout.me,null);
        list.add(vnews);
        list.add(vfriend);
        list.add(vmoney);
        list.add(vme);
        adapter=new PagerAdapter() {
            @Override
            public int getCount() {
                return list.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view==object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view=list.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(list.get(position));
            }
        };
        view_pager.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        resetImg();
        switch (v.getId()){
            case R.id.ll_news:
                view_pager.setCurrentItem(0);
                img_news.setImageResource(R.drawable.tab_icon_news_light);
                break;
            case R.id.ll_friend:
                view_pager.setCurrentItem(1);
                img_friend.setImageResource(R.drawable.tab_icon_friend_light);
                break;
            case R.id.ll_money:
                view_pager.setCurrentItem(2);
                img_money.setImageResource(R.drawable.tab_icon_money_light);
                break;
            case R.id.ll_me:
                view_pager.setCurrentItem(3);
                img_me.setImageResource(R.drawable.tab_icon_me_light);
                break;
        }

    }

    private void resetImg() {
        img_news.setImageResource(R.drawable.tab_icon_news_dark);
        img_friend.setImageResource(R.drawable.tab_icon_friend_dark);
        img_me.setImageResource(R.drawable.tab_icon_me_dark);
        img_money.setImageResource(R.drawable.tab_icon_money_dark);
    }
}



简单讲解以上代码:

初始化布局initView()这个方法主要是绑定各种布局与把数据添加进入列表,初始化adapter.

initEvent():为底部的LinearLayout添加点击事件,添加viewPager监听事件

onclick():实现点击事件,主要是把图片点亮

resetImg():把各个图片初始化变暗


2、用fragment实现


创建四个fragment分别继承于Fragment:newsfrag     friendfrag  moneyfrag  myfrag

举例一个(其他类似):

newsfrag:

package com.lm2.newsapp.fragmentfile;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lm2.newsapp.R;

/**
 * Created by Hp on 2017/4/14.
 */

public class newsfrag extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news, container, false);
    }
}

MainAcitivity:

package com.lm2.newsapp;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.lm2.newsapp.fragmentfile.friendfrag;
import com.lm2.newsapp.fragmentfile.moneyfrag;
import com.lm2.newsapp.fragmentfile.myfrag;
import com.lm2.newsapp.fragmentfile.newsfrag;

public class fragment extends FragmentActivity implements View.OnClickListener{
    private LinearLayout ll_news,ll_friend,ll_money,ll_me;
    private ImageButton imgnews,imgfriend,imgmoney,imgme;
    private FrameLayout fl;
    private Fragment news_frag,friend_frag,money_frag,my_frag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);
        initView();
        initEvent();
        setSelected(0);
    }

    private void initEvent() {
        ll_friend.setOnClickListener(this);
        ll_news.setOnClickListener(this);
        ll_money.setOnClickListener(this);
        ll_me.setOnClickListener(this);

    }

    private void initView() {
        ll_friend=(LinearLayout)findViewById(R.id.ll_friend);
        ll_me=(LinearLayout)findViewById(R.id.ll_me);
        ll_money=(LinearLayout)findViewById(R.id.ll_money);
        ll_news=(LinearLayout)findViewById(R.id.ll_news);

        imgfriend=(ImageButton)findViewById(R.id.img_friend);
        imgnews=(ImageButton)findViewById(R.id.img_news);
        imgmoney=(ImageButton)findViewById(R.id.img_money);
        imgme=(ImageButton)findViewById(R.id.img_me);
    }

public void setSelected(int position){
    FragmentManager fm=getSupportFragmentManager();
    FragmentTransaction ft=fm.beginTransaction();
    hidefrag(ft);
    switch (position){
        case 0:
            if(news_frag==null){
                news_frag=new newsfrag();
                ft.add(R.id.fl,news_frag);
            }
            else {
                ft.show(news_frag);
            }
            imgnews.setImageResource(R.drawable.tab_icon_news_light);
            break;
        case 1:
            if(friend_frag==null){
                friend_frag=new friendfrag();
                ft.add(R.id.fl,friend_frag);
            }
            else {
                ft.show(friend_frag);
            }
            imgfriend.setImageResource(R.drawable.tab_icon_friend_light);
            break;
        case 2:
            if(money_frag==null){
                money_frag=new moneyfrag();
                ft.add(R.id.fl,money_frag);
            }
            else {
                ft.show(money_frag);
            }
            imgmoney.setImageResource(R.drawable.tab_icon_money_light);
            break;
        case 3:
            if(my_frag==null){
                my_frag=new myfrag();
                ft.add(R.id.fl,my_frag);
            }
            else {
                ft.show(my_frag);
            }
            imgme.setImageResource(R.drawable.tab_icon_me_light);
            break;
    }
    ft.commit();

}



    @Override
    public void onClick(View v) {

        resetImg();
        switch (v.getId()){
            case R.id.ll_news:
                setSelected(0);
                break;
         case R.id.ll_friend:
                setSelected(1);
                break;
            case R.id.ll_money:
                setSelected(2);
                break;
            case R.id.ll_me:
                setSelected(3);
                break;
        }

    }

    private void hidefrag(FragmentTransaction transaction) {
        if(news_frag!=null){
            transaction.hide(news_frag);
        }
        if(friend_frag!=null){
            transaction.hide(friend_frag);
        }
        if(money_frag!=null){
            transaction.hide(money_frag);
        }
        if(my_frag!=null){
            transaction.hide(my_frag);
        }
    }
    private void resetImg() {
        imgme.setImageResource(R.drawable.tab_icon_me_dark);
        imgmoney.setImageResource(R.drawable.tab_icon_money_dark);
        imgnews.setImageResource(R.drawable.tab_icon_news_dark);
        imgfriend.setImageResource(R.drawable.tab_icon_friend_dark);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值