滑动视图 Swipe Views
滑动视图 Swipe Views是我们在android开发中常见的内容导航方式,可以很直观的引导用户得到想要的内容。
滑动视图 Swipe Views的实现主要靠 ViewPager 来实现!
ViewPager 在V4支持包中被添加进来,通过在xml布局文件中声明ViewPager,再在Activity中实例化ViewPager,并设置PagerAdapter来实现页面的侧滑效果。
PagerAdapter 主要有三种:
PagerAdapter 基础类
FragmentPagerAdapter 基于Fragment组织内容,少量 可预知的内容
- FragmentStatePagerAdapter 可以保存Fragment的state状态,当不需要时间,销毁Fragment,减少内存的消耗
这里就以FragmentStatePagerAdapter为例!
1.在布局文件中声明ViewPager
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
2.在Activity 中实例化并定义 设置适配器
package com.example.swipeviews;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
//ViewPager 来自V4 支持包,所以这里继承FragmentActivity
public class MainActivity extends FragmentActivity {
// Viewpager
private ViewPager mViewPager;
// Pager适配器
private MyPagerAdapter myPagerAdapter;
// 图片的URL
private String[] paths = {
"http://d.hiphotos.bdimg.com/album/pic/item/34fae6cd7b899e51dca31fbb40a7d933c8950d6b.jpg",
"http://imgsrc.baidu.com/forum/w%3D580/sign=97543e82b6119313c743ffb855380c10/fc0a12f41bd5ad6e19d394aa85cb39dbb6fd3c5d.jpg",
"http://thumbnail2.jiaoyoudns.com/mfs.jiaoyoudns.com/test/sld/91/0391/1_tuku_1_9_1395000391.jpg=-=750_750_0_thumbnails.jpg",
"http://d.hiphotos.bdimg.com/album/pic/item/34fae6cd7b899e51dca31fbb40a7d933c8950d6b.jpg",
"http://img5.duitang.com/uploads/item/201405/02/20140502190021_Bkau2.jpeg" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 实例化ViewPager 和 PagerAdapter ,并设置适配器
mViewPager = (ViewPager) findViewById(R.id.pager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(myPagerAdapter);
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
ImageFragment imageFragment = new ImageFragment();
Bundle args = new Bundle();
// Fragment 传递信息
args.putString(ImageFragment.IMAGE_PATH, paths[position]);
imageFragment.setArguments(args);
return imageFragment;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return paths.length;
}
@Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return "krystal---->" + position;
}
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
3.定义Fragment类及其布局
package com.example.swipeviews;
import com.example.swipeviews.LoadImage.ImageLoadCallback;
import android.graphics.Bitmap;
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.ImageView;
public class ImageFragment extends Fragment {
static final String IMAGE_PATH="ImagePath";
private ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.image_fragment, null, false);
imageView=(ImageView)view.findViewById(R.id.imageView);
Bundle bundle=getArguments();
String url=bundle.getString(IMAGE_PATH);
LoadImage.loadImage(url, new ImageLoadCallback() {
@Override
public void updateImage(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
} );
return view;
}
}
<RelativeLayout 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" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="8dp"
android:scaleType="fitCenter"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
4.在网络上下载图片的帮助类 LoadImage.java
package com.example.swipeviews;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
//定义回调接口,让调用者可以实现对于UI的修改
public class LoadImage {
public LoadImage() {
// TODO Auto-generated constructor stub
}
public static void loadImage(final String url,
final ImageLoadCallback callback) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Bitmap bitmap = (Bitmap) msg.obj;
Log.i("TAG", "2.handler ");
// 回调函数
callback.updateImage(bitmap);
}
};
new Thread(new Runnable() {
@Override
public void run() {
Log.i("TAG", "1.请求图片资源00" + url);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
Log.i("TAG", "1.1 "
+ httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
byte[] data = EntityUtils.toByteArray(httpResponse
.getEntity());
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
Log.i("TAG", "1.5.发送Bitmap");
Message message = Message.obtain();
message.obj = bitmap;
// 错误 handler.handleMessage(message);
// android异常:android.view.ViewRootImpl$CalledFromWrongThreadException
// 只能在UI主线程改变组件状态
// 这里只是传送消息
handler.sendMessage(message);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}).start();
}
// 設置一個回調接口
public interface ImageLoadCallback {
public void updateImage(Bitmap bitmap);
}
}
5.运行效果
滑动切换不同Fragment,异步从网络上下载图片,ViewPager有预加载机制。
6.添加Tab in ActionBar
- 在Actionbar中常见Tab (To create tabs using ActionBar)
// ActionBar中添加Tab支持
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
- 设置TabListener,添加Tab,并添加Listener
// 设置tab监听器
ActionBar.TabListener listener = new ActionBar.TabListener() {
@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
// When the tab is selected, switch to the
// corresponding page in the ViewPager.
// 通过Tab的位置,定位到对应的Fragment
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
};
for (int i = 0; i < paths.length; i++) {
actionBar.addTab(actionBar.newTab().setText("krystal" + i)
.setTabListener(listener));
}
- ViewPager设置OnPageChangeListener,实现通过滑动切换Tab
// 监听滑动事件,实现滑动切换页面
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
@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
}
});
}
- 新的运行结果