Android基于ViewPager Fragment实现选项卡

先给大家展示效果图:

1.新建TestFragmen继承Fragment

public class TestFragment extends Fragment {
  private static final String TAG = "TestFragment";
  private String hello;// = "hello android";
  private String defaultHello = "default value";
  private Map<string, object=""> maplist;
  static TestFragment newInstance(String s, Map<string, object=""> map) {
    TestFragment newFragment = new TestFragment();
    // Bundle bundle = new Bundle();
    // bundle.putString("hello", s);
    // newFragment.setArguments(bundle);
    final SerializableMap myMap=new SerializableMap();
    myMap.setMap(map);
    Bundle bundle = new Bundle();
    bundle.putSerializable("map", myMap);
    newFragment.setArguments(bundle);
    return newFragment;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "TestFragment-----onCreate");
    Bundle args = getArguments();
   // hello = args != null ? args.getString("hello") : defaultHello;
    Bundle bundle = getArguments();
    SerializableMap serializableMap = (SerializableMap) bundle.get("map");
    maplist =serializableMap.getMap();
  }
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    Log.d(TAG, "TestFragment-----onCreateView");
    View view = inflater.inflate(R.layout.lay1, container, false);
    // TextView viewhello = (TextView) view.findViewById(R.id.tv_hello);
    //viewhello.setText(maplist.get("userid")+"time");
    ListView lv = (ListView) view.findViewById(R.id.listView3);
    ContactAdapter hc = new ContactAdapter(getActivity().getApplicationContext(),getContact());
    lv.setAdapter(hc);
    lv.setCacheColorHint(0);
    return view;
  }
  private ArrayList<contact> getContact(){
    ArrayList<contact> hcList = new ArrayList<contact>();
    for(int i=0;i<10;i++)
    {
    Contact c0 = new Contact();
    c0.setTxPath(R.drawable.more_game+"");
    c0.setName(maplist.get("userid")+" 年龄:"+maplist.get("age"));
    hcList.add(c0);
    }
    return hcList;
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "TestFragment-----onDestroy");
  }
}
</contact></contact></contact></string,></string,>

2.MyFragmentPagerAdapter继承FragmentPagerAdapter

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
  private ArrayList<fragment> fragmentsList;
  public MyFragmentPagerAdapter(FragmentManager fm) {
    super(fm);
  }
  public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<fragment> fragments) {
    super(fm);
    this.fragmentsList = fragments;
  }
  @Override
  public int getCount() {
    return fragmentsList.size();
  }
  @Override
  public Fragment getItem(int arg0) {
    return fragmentsList.get(arg0);
  }
  @Override
  public int getItemPosition(Object object) {
    return super.getItemPosition(object);
  }
}
</fragment></fragment>

3.MainActivity 要继承FragmentActivity

public class MainActivity extends FragmentActivity {
  private static final String TAG = "MainActivity";
  private ViewPager mPager;
  private ArrayList<fragment> fragmentsList;
  private ImageView ivBottomLine;
  private TextView tvTabActivity, tvTabGroups, tvTabFriends, tvTabChat;
  private int currIndex = 0;
  private int bottomLineWidth;
  private int offset = 0;
  private int position_one;
  private int position_two;
  private int position_three;
  private Resources resources;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    resources = getResources();
    InitWidth();
    InitTextView();
    InitViewPager();
  }
  private void InitTextView() {
    tvTabActivity = (TextView) findViewById(R.id.tv_tab_activity);
    tvTabGroups = (TextView) findViewById(R.id.tv_tab_groups);
    tvTabFriends = (TextView) findViewById(R.id.tv_tab_friends);
    tvTabChat = (TextView) findViewById(R.id.tv_tab_chat);
    tvTabActivity.setOnClickListener(new MyOnClickListener(0));
    tvTabGroups.setOnClickListener(new MyOnClickListener(1));
    tvTabFriends.setOnClickListener(new MyOnClickListener(2));
    tvTabChat.setOnClickListener(new MyOnClickListener(3));
  }
  private void InitViewPager() {
    mPager = (ViewPager) findViewById(R.id.vPager);
    fragmentsList = new ArrayList<fragment>();
    Map<string, object=""> paramMap = new HashMap<string, object="">();
    paramMap.put("userid","小洪");
    paramMap.put("age",23);
    Map<string, object=""> paramMap2 = new HashMap<string, object="">();
    paramMap2.put("userid","vatty");
    paramMap2.put("age",24);
    Map<string, object=""> paramMap3 = new HashMap<string, object="">();
    paramMap3.put("userid","小明");
    paramMap3.put("age",25);
    Map<string, object=""> paramMap4 = new HashMap<string, object="">();
    paramMap4.put("userid","hongshengpeng.com");
    paramMap4.put("age",26);
    Fragment activityfragment = TestFragment.newInstance("Hello Activity.",paramMap);
    Fragment groupFragment = TestFragment.newInstance("Hello Group.",paramMap2);
    Fragment friendsFragment=TestFragment.newInstance("Hello Friends.",paramMap3);
    Fragment chatFragment=TestFragment.newInstance("Hello Chat.",paramMap4);
    fragmentsList.add(activityfragment);
    fragmentsList.add(groupFragment);
    fragmentsList.add(friendsFragment);
    fragmentsList.add(chatFragment);
    mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList));
    mPager.setCurrentItem(0);
    mPager.setOnPageChangeListener(new MyOnPageChangeListener());
  }
  private void InitWidth() {
    ivBottomLine = (ImageView) findViewById(R.id.iv_bottom_line);
    bottomLineWidth = ivBottomLine.getLayoutParams().width;
    Log.d(TAG, "cursor imageview width=" + bottomLineWidth);
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int screenW = dm.widthPixels;
    offset = (int) ((screenW / 4.0 - bottomLineWidth) / 2);
    Log.i("MainActivity", "offset=" + offset);
    position_one = (int) (screenW / 4.0);
    position_two = position_one * 2;
    position_three = position_one * 3;
  }
  public class MyOnClickListener implements View.OnClickListener {
    private int index = 0;
    public MyOnClickListener(int i) {
      index = i;
    }
    @Override
    public void onClick(View v) {
      mPager.setCurrentItem(index);
    }
  };
  public class MyOnPageChangeListener implements OnPageChangeListener {
    @Override
    public void onPageSelected(int arg0) {
      Animation animation = null;
      switch (arg0) {
      case 0:
        if (currIndex == 1) {
          animation = new TranslateAnimation(position_one, 0, 0, 0);
          tvTabGroups.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 2) {
          animation = new TranslateAnimation(position_two, 0, 0, 0);
          tvTabFriends.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 3) {
          animation = new TranslateAnimation(position_three, 0, 0, 0);
          tvTabChat.setTextColor(resources.getColor(R.color.lightwhite));
        }
        tvTabActivity.setTextColor(resources.getColor(R.color.white));
        break;
      case 1:
        if (currIndex == 0) {
          animation = new TranslateAnimation(0, position_one, 0, 0);
          tvTabActivity.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 2) {
          animation = new TranslateAnimation(position_two, position_one, 0, 0);
          tvTabFriends.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 3) {
          animation = new TranslateAnimation(position_three, position_one, 0, 0);
          tvTabChat.setTextColor(resources.getColor(R.color.lightwhite));
        }
        tvTabGroups.setTextColor(resources.getColor(R.color.white));
        break;
      case 2:
        if (currIndex == 0) {
          animation = new TranslateAnimation(0, position_two, 0, 0);
          tvTabActivity.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 1) {
          animation = new TranslateAnimation(position_one, position_two, 0, 0);
          tvTabGroups.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 3) {
          animation = new TranslateAnimation(position_three, position_two, 0, 0);
          tvTabChat.setTextColor(resources.getColor(R.color.lightwhite));
        }
        tvTabFriends.setTextColor(resources.getColor(R.color.white));
        break;
      case 3:
        if (currIndex == 0) {
          animation = new TranslateAnimation(0, position_three, 0, 0);
          tvTabActivity.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 1) {
          animation = new TranslateAnimation(position_one, position_three, 0, 0);
          tvTabGroups.setTextColor(resources.getColor(R.color.lightwhite));
        } else if (currIndex == 2) {
          animation = new TranslateAnimation(position_two, position_three, 0, 0);
          tvTabFriends.setTextColor(resources.getColor(R.color.lightwhite));
        }
        tvTabChat.setTextColor(resources.getColor(R.color.white));
        break;
      }
      currIndex = arg0;
      animation.setFillAfter(true);
      animation.setDuration(300);
      ivBottomLine.startAnimation(animation);
    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }
    @Override
    public void onPageScrollStateChanged(int arg0) {
    }
  }
}</string,></string,></string,></string,></string,></string,></string,></string,></fragment></fragment>

4.分别新建lay1.xml、 lay2.xml 、lay3.xml

lay1.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" android:orientation="vertical">
  <textview android:id="@+id/tv_hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:visibility="gone">
   <listview android:id="@+id/listView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:cachecolorhint="@android:color/transparent" android:divider="@drawable/reader_item_divider" android:listselector="@android:color/transparent">
        </listview>
</textview></linearlayout>

lay2.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#FF8684">
</linearlayout>

lay3.xml与lay2.xml类型

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#1586FF">
</linearlayout>

main.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:umadsdk="http://schemas.android.com/apk/res/com.LoveBus" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
  <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <linearlayout android:layout_width="match_parent" android:layout_height="48dip" android:background="@drawable/android_title_bg">
      <imageview android:id="@+id/imageView1" android:layout_width="36dip" android:layout_height="36dip" android:layout_gravity="center_vertical" android:layout_marginleft="10dip" android:src="@drawable/more_game">
      <textview android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginleft="10dip" android:text="乐够GO" android:textappearance="?android:attr/textAppearanceLarge">
      <imageview android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:paddingleft="10dip" android:src="@drawable/status_online" android:visibility="gone">
    </imageview></textview></imageview></linearlayout>
    <linearlayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingbottom="5dip" android:paddingtop="10dip" android:background="@color/coral">
      <textview android:id="@+id/tv_tab_activity" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_1" android:textcolor="@color/white" android:textsize="18sp">
      <textview android:id="@+id/tv_tab_groups" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_2" android:textcolor="@color/lightwhite" android:textsize="18sp">
      <textview android:id="@+id/tv_tab_friends" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_3" android:textcolor="@color/lightwhite" android:textsize="18sp">
      <textview android:id="@+id/tv_tab_chat" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_4" android:textcolor="@color/lightwhite" android:textsize="18sp">
    </textview></textview></textview></textview></linearlayout>
    <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:orientation="vertical" android:paddingbottom="3dip">
      <imageview android:id="@+id/iv_bottom_line" android:layout_width="40dip" android:layout_height="2dip" android:layout_marginleft="20dip" android:scaletype="matrix" android:src="#fff">
    </imageview></linearlayout>
  </linearlayout>
</android.support.v4.view.viewpager></linearlayout>

ps:ViewPager + Fragment实现滑动标签页

ViewPager 结合Fragment实现一个Activity里包含多个可滑动的标签页,每个标签页可以有独立的布局及响应。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
      android:id="@+id/tv_guid1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1.0"
      android:gravity="center"
      android:text="特性1"
      android:textSize="18sp"/>
    <TextView
      android:id="@+id/tv_guid2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1.0"
      android:gravity="center"
      android:text="特性2"
      android:textSize="18sp"/>
    <TextView
      android:id="@+id/tv_guid3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1.0"
      android:gravity="center"
      android:text="特性3 "
      android:textSize="18sp"/>
    <TextView
      android:id="@+id/tv_guid4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1.0"
      android:gravity="center"
      android:text="特性4"
      android:textSize="18sp"/>
  </LinearLayout>
  <ImageView
    android:id="@+id/cursor"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="matrix"
    android:src="@drawable/cursor"/>
  <android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:flipInterval="30"
    android:persistentDrawingCache="animation"/>
</LinearLayout> 

MainActivity.java

package com.example.viewpagernfragment;
import java.util.ArrayList;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
  private ViewPager mPager;
  private ArrayList<Fragment> fragmentList;
  private ImageView image;
  private TextView view1, view2, view3, view4;
  private int currIndex;//当前页卡编号
  private int bmpW;//横线图片宽度
  private int offset;//图片移动的偏移量
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    InitTextView();
    InitImage();
    InitViewPager();
  }
  /*
   * 初始化标签名
   */
  public void InitTextView(){
    view1 = (TextView)findViewById(R.id.tv_guid1);
    view2 = (TextView)findViewById(R.id.tv_guid2);
    view3 = (TextView)findViewById(R.id.tv_guid3);
    view4 = (TextView)findViewById(R.id.tv_guid4);
    view1.setOnClickListener(new txListener(0));
    view2.setOnClickListener(new txListener(1));
    view3.setOnClickListener(new txListener(2));
    view4.setOnClickListener(new txListener(3));
  }
  public class txListener implements View.OnClickListener{
    private int index=0;
    public txListener(int i) {
      index =i;
    }
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
      mPager.setCurrentItem(index);
    }
  }
  /*
   * 初始化图片的位移像素
   */
  public void InitImage(){
    image = (ImageView)findViewById(R.id.cursor);
    bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth();
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int screenW = dm.widthPixels;
    offset = (screenW/4 - bmpW)/2;
    //imgageview设置平移,使下划线平移到初始位置(平移一个offset)
    Matrix matrix = new Matrix();
    matrix.postTranslate(offset, 0);
    image.setImageMatrix(matrix);
  }
  /*
   * 初始化ViewPager
   */
  public void InitViewPager(){
    mPager = (ViewPager)findViewById(R.id.viewpager);
    fragmentList = new ArrayList<Fragment>();
    Fragment btFragment= new ButtonFragment();
    Fragment secondFragment = TestFragment.newInstance("this is second fragment");
    Fragment thirdFragment = TestFragment.newInstance("this is third fragment");
    Fragment fourthFragment = TestFragment.newInstance("this is fourth fragment");
    fragmentList.add(btFragment);
    fragmentList.add(secondFragment);
    fragmentList.add(thirdFragment);
    fragmentList.add(fourthFragment);
    //给ViewPager设置适配器
    mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));
    mPager.setCurrentItem(0);//设置当前显示标签页为第一页
    mPager.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器
  }
  public class MyOnPageChangeListener implements OnPageChangeListener{
    private int one = offset *2 +bmpW;//两个相邻页面的偏移量
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
      // TODO Auto-generated method stub
    }
    @Override
    public void onPageScrollStateChanged(int arg0) {
      // TODO Auto-generated method stub
    }
    @Override
    public void onPageSelected(int arg0) {
      // TODO Auto-generated method stub
      Animation animation = new TranslateAnimation(currIndex*one,arg0*one,0,0);//平移动画
      currIndex = arg0;
      animation.setFillAfter(true);//动画终止时停留在最后一帧,不然会回到没有执行前的状态
      animation.setDuration(200);//动画持续时间0.2秒
      image.startAnimation(animation);//是用ImageView来显示动画的
      int i = currIndex + 1;
      Toast.makeText(MainActivity.this, "您选择了第"+i+"个页卡", Toast.LENGTH_SHORT).show();
    }
  }
  @Override
  public 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;
  }
} 

谷歌官方认为,ViewPager应该和Fragment一起使用时,此时ViewPager的适配器是FragmentPagerAdapter,当你实现一个FragmentPagerAdapter,你必须至少覆盖以下方法:

getCount()

getItem()

如果ViewPager没有和Fragment一起,ViewPager的适配器是PagerAdapter,它是基类提供适配器来填充页面ViewPager内部,当你实现一个PagerAdapter,你必须至少覆盖以下方法:

instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)
[java] view plaincopy
package com.example.viewpagernfragment;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
  ArrayList<Fragment> list;
  public MyFragmentPagerAdapter(FragmentManager fm,ArrayList<Fragment> list) {
    super(fm);
    this.list = list;
  }
  @Override
  public int getCount() {
    return list.size();
  }
  @Override
  public Fragment getItem(int arg0) {
    return list.get(arg0);
  }
}
[java] view plaincopy
package com.example.viewpagernfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class ButtonFragment extends Fragment{
  Button myButton;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.guide_1, container, false);//关联布局文件
    myButton = (Button)rootView.findViewById(R.id.mybutton);//根据rootView找到button
    //设置按键监听事件
    myButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        Toast.makeText(ButtonFragment.this.getActivity(), "button is click!", Toast.LENGTH_SHORT).show();
      }
    });
    return rootView;
  }
}
[java] view plaincopy
package com.example.viewpagernfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestFragment extends Fragment {
  private static final String TAG = "TestFragment";
  private String hello;// = "hello android";
  private String defaultHello = "default value";
  static TestFragment newInstance(String s) {
    TestFragment newFragment = new TestFragment();
    Bundle bundle = new Bundle();
    bundle.putString("hello", s);
    newFragment.setArguments(bundle);
    //bundle还可以在每个标签里传送数据
    return newFragment;
  }
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    Log.d(TAG, "TestFragment-----onCreateView");
    Bundle args = getArguments();
    hello = args != null ? args.getString("hello") : defaultHello;
    View view = inflater.inflate(R.layout.guide_2, container, false);
    TextView viewhello = (TextView) view.findViewById(R.id.tv);
    viewhello.setText(hello);
    return view;
  }
} 

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#ff0000ff" >
  <Button
    android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hit me"
    android:gravity="center"/>
</RelativeLayout>
[html] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:background="#158684" >
  <TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />
</RelativeLayout> 
时间: 2015-11-23

android 中viewpager+fragment仿微信底部TAG完美渐变

viewpager+fragment仿微信底部TAG完美渐变,在图片渐变的同时字的颜色也在变,注意,是渐变哦! 效果图: activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:zhy="http://schemas.android.com/apk/res/com.Sing.weixin" xmlns:tools="

Android App中使用ViewPager+Fragment实现滑动切换效果

在android应用中,多屏滑动是一种很常见的风格,没有采用viewpager的代码实现会很长,如果采用ViewPager,代码就会短很多,但是使用ViewPager也有弊端:需要导入android-support-v4.jar.细节无法控制.不过现在情况已经不一样了,android-support-v4中提供了很多实用的功能,以至于现在新建一个android工程默认都会导入这个jar包.那我们就也采用viewpager来做滑动吧.另外一个概念就是Fragment和FragmentActivit

Android中ViewPager实现滑动指示条及与Fragment的配合

自主实现滑动指示条 先上效果图: 1.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

Android App在ViewPager中使用Fragment的实例讲解

据说Android最推荐的是在ViewPager中使用FragMent,即ViewPager中的页面不像前面那样用LayoutInflater直接从布局文件加载,而是一个个Fragment.注意这里的Fragment 是android.support.v4.view包里的Fragment,而不是android.app包里的Fragment. 使用v4包里的Fragment的Activity必须继承自FragmentActivity. 其实使用Fragment与前面不使用Fragment非常类似:

Android仿微信Viewpager-Fragment惰性加载(lazy-loading)

前言 今天起床,拿起手机开机第一时间当然是打开微信了,左右滑动Viewpager,发现它使用了一种叫惰性加载,或者说懒加载(lazy-loading)的方式加载Viewpager中的Fragment.效果如图: 什么是lazy-loading呢?顾名思义就是在必要的时候才加载,否则不进行View的绘制和数据的加载.原因是Viewpager一次只会显示一个页卡,那么刚开始的时候,只需加载第一张Fragment页卡,其他的不加载,当用户向右滑动切换再进行加载.因为其他Fragment对于用户来说是不

Android 开发之BottomBar+ViewPager+Fragment实现炫酷的底部导航效果

BottomBar BottomBar是Github上的一个开源框架,因为从1.3.3开始不支持fragments了,要自己配置,弄了很久,不管是app的fragment还是V4 的程序总是总是闪退.于是就用这种方式实现了,效果还不错.github有详细说明,多余的就不说了. 这个roughike是这个项目的所有者(大神致敬). 我用的是Android studio开发,fragment全部导的V4的包(以为最开始就支持的是v4的,后面也支持了app.fragment). 首先是dependen

Android实现Tab布局的4种方式(Fragment+TabPageIndicator+ViewPager)

Android现在实现Tab类型的界面方式越来越多,今天就把常见的实现方式给大家来个总结.目前写了: 1.传统的ViewPager实现 2.FragmentManager+Fragment实现 3.ViewPager+FragmentPagerAdapter实现 4.TabPageIndicator+ViewPager+FragmentPagerAdapter 1.传统的ViewPager实现 主要就是ViewPager+ViewAdapter这个还是比较常见的,就不多说了 效果图: 代码: p

Android中ViewPager和Fragment的使用

小案例 XML中 <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v4.view.ViewPager> 创建Fragment fragments = new Arr

Android App中ViewPager与Fragment结合的一些问题解决

在了解ViewPager的工作原理之前,先回顾ListView的工作原理: ListView只有在需要显示某些列表项时,它才会去申请可用的视图对象:如果为所有的列表项数据创建视图对象,会浪费内存: ListView找谁去申请视图对象呢? 答案是adapter.adapter是一个控制器对象,负责从模型层获取数据,创建并填充必要的视图对象,将准备好的视图对象返回给ListView: 首先,通过调用adapter的getCount()方法,ListView询问数组列表中包含多少个对象(为避免出现数组

Android中ViewPager获取当前显示的Fragment

前言 在项目中,有时会用到在ViewPager中显示同样类型的Fragment,同时这样的Fragment的个数是动态的,但是PagerAdapter没有给我们提供getCurrentFragment类似的方法.下面就给大家介绍下Android中ViewPager获取当前显示的Fragment的方法,一起看看吧. 一.使用 getSupportFragmentManager().findFragmentByTag()方法 Viewpager + FragmentPagerAdapter 情况下

Android 中ViewPager中使用WebView的注意事项

Android 中ViewPager中使用WebView的注意事项 前言: 今天在做项目时遇到了一个小问题 首先使用ViewPager显示多个页面,然后在每个页面上使用Fragment显示数据,其中有一部分数据是通过WebView加载的Html标签. 具体xml布局如下 <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.andr

Android 中ViewPager重排序与更新实例详解

Android 中ViewPager重排序与更新实例详解 最近的项目中有栏目订阅功能,在更改栏目顺序以后需要更新ViewPager.类似于网易新闻的频道管理. 在重新排序之后调用了PagerAdapter的notifyDataSetChanged方法,发现ViewPager并没有更新,于是我开始跟踪源码,在调用PagerAdapter的notifyDataSetChanged方法后,会触发Viewpager的dataSetChanged方法. void dataSetChanged() { //

Android中findViewById获取控件返回为空问题怎么解决

在Android程序中,有时候需要加载非原来activity中xml布局中的控件,来使Android程序的界面更加丰富. 我本身是在使用ViewFlipper中遇到的问题. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); inflater=(LayoutInflater)getSystemService(LAYO

Android中如何获取视频文件的截图、缩略图

背景 公司最近要求给我负责的APP加上视频录制和发布的功能,我简单的完成了基本的录制和视频压缩功能,后来发现发布接口需要上传视频的截图,网上搜索了一下资料,在这里整理一下. 代码实现 /** * 获取视频文件截图 * * @param path 视频文件的路径 * @return Bitmap 返回获取的Bitmap */ public static Bitmap getVideoThumb(String path) { MediaMetadataRetriever media = new Me

Android中实现EditText密码显示隐藏的方法

在Google发布了support:design:23+以后我们发现有这么一个东西TextInputLayout,先看下效果图: <android.support.design.widget.TextInputLayout android:id="@+id/pwdLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:passw

Android中ScrollView嵌套GridView显示不全解决方法

Android中ScrollView嵌套GridView显示不全解决方法 由于ScrollView和GridView这两款控件都自带滚动条,一起使用GridView会显示不全 解决方法:自定义gridview 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Android中ViewPager实现滑动条及与Fragment结合的实例教程

自主实现滑动指示条 先上一个基本效果图: 1.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="m