Android仿百度贴吧看帖滑动返回效果

来源:互联网 发布:大数据研究现状 编辑:程序博客网 时间:2024/05/29 10:16
前几天更新百度贴吧后,发现看帖时的滑动返回效果挺好的,在做公司项目的查找功能时就研究并使用了这种效果,实现起来其实挺简单的,代码是从公司项目里提取出来的,所以就多增送一个搜索界面的AutoCompleteTextView控件使用。
先简单介绍一下原理:
滑动效果:使用Fragment+ViewPager实现,将两个Fragment添加到ViewPager中,第一个Fragment设置成透明背景,第二个Fragment是自己想要的页面;监听ViewPager滑动事件,通过参数判断滑动位置,改变背景透明度并在页面全部划过时结束当前页面;增加页面跳转和返回时的动态效果。

搜索功能中AutoCompleteTextView控件的使用:动态监听AutoCompleteTextView中内容变化,保存并显示最近搜索的10条记录,监听弹出列表的点击事件等。

下面直接上代码:

1、主页面布局

<?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:id="@+id/blank_linear"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#44000000"      android:orientation="vertical" >        <android.support.v4.view.ViewPager        android:id="@+id/viewPager1"        android:layout_width="match_parent"        android:layout_height="match_parent" >    </android.support.v4.view.ViewPager></LinearLayout>
2、使用Fragment+ViewPager实现实现滑动效果

package com.cx.intentdemo;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;import android.widget.LinearLayout;public class MainActivity extends FragmentActivity{private ViewPager viewPager;private LinearLayout blankLinear;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();setListener();}private void initView() {// TODO Auto-generated method stubviewPager = (ViewPager) findViewById(R.id.viewPager1);blankLinear = (LinearLayout) findViewById(R.id.blank_linear);  }private void initData() {// TODO Auto-generated method stubviewPager.setAdapter(adapter);viewPager.setCurrentItem(1, false);viewPager.setOnPageChangeListener(changeListener);}private void setListener() {// TODO Auto-generated method stub}private FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {public int getCount() {return 2;}public Fragment getItem(int position) {Fragment fragment = null;switch (position) {case 0:fragment = new BlankFragment();break;case 1:fragment = new SearchFragment();break;}return fragment;}};private SimpleOnPageChangeListener changeListener = new SimpleOnPageChangeListener() {public void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {//修改背景透明度blankLinear.getBackground().setAlpha((int) (positionOffset * 500));//滑动到if (position == 0 && positionOffset == 0.0) {finish();}};};@Overridepublic void onBackPressed() {finish();overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);};}
3、透明Fragment布局
<?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"    android:background="#01000000"      android:orientation="vertical" ></LinearLayout>
4、透明Fragment界面
package com.cx.intentdemo;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class BlankFragment extends Fragment{@Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,              Bundle savedInstanceState) {  View v = inflater.inflate(R.layout.blank_fragment, container, false);        return v;      }        @Override      public void onActivityCreated(Bundle savedInstanceState) {          super.onActivityCreated(savedInstanceState);      } }

5、搜索Fragment布局

<?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"    android:background="#ddd"    android:orientation="vertical" >    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#f1f1f1" >        <AutoCompleteTextView            android:id="@+id/autoCompleteTextView1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentLeft="true"            android:layout_alignParentTop="true"            android:layout_marginRight="10dp"            android:layout_marginLeft="10dp"            android:layout_toLeftOf="@+id/btn_search"            android:background="@drawable/bg_edittext_round_2"            android:ems="10"            android:hint="输入关键字..."            android:paddingLeft="30dp" >            <requestFocus />        </AutoCompleteTextView>        <ImageView            android:id="@+id/imageView1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentLeft="true"            android:layout_centerVertical="true"            android:layout_marginLeft="20dp"            android:src="@drawable/search" />        <Button            android:id="@+id/btn_search"            android:layout_width="50dp"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_centerVertical="true"            android:background="@drawable/btn_submit"            android:layout_marginRight="10dp"            android:text="搜索" />    </RelativeLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="11" ><ListView        android:id="@+id/lv_search"        android:layout_width="match_parent"        android:layout_height="wrap_content" >    </ListView>            </LinearLayout></LinearLayout>

6、搜索Fragment界面功能实现
package com.cx.intentdemo;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.support.v4.app.Fragment;import android.text.Editable;import android.text.TextWatcher;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnFocusChangeListener;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.AutoCompleteTextView;import android.widget.Button;public class SearchFragment extends Fragment {private AutoCompleteTextView acTextView;  private Button btnSearch;private int length;      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,              Bundle savedInstanceState) {          return inflater.inflate(R.layout.search, container, false);      }        @Override      public void onActivityCreated(Bundle savedInstanceState) {          super.onActivityCreated(savedInstanceState);                  initView();initData();setListener();    }         private void initView() {// TODO Auto-generated method stubacTextView = (AutoCompleteTextView) getView().findViewById(R.id.autoCompleteTextView1);btnSearch = (Button) getView().findViewById(R.id.btn_search);}private void initData() {// TODO Auto-generated method stub}private void setListener() {// TODO Auto-generated method stubacTextView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubacTextView.showDropDown();initAutoComplete();}});//内容变化监听acTextView.addTextChangedListener(new TextWatcher() {@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {// TODO Auto-generated method stubinitAutoComplete();}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {// TODO Auto-generated method stub}@Overridepublic void afterTextChanged(Editable s) {// TODO Auto-generated method stub}});//最近搜索列表点击事件acTextView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {getData();}});btnSearch.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsaveHistory();getData();}});}/** * 通过输入内容查找数据 */private void getData(){//一般为网路请求}/** * 显示最近10条搜索内容 */private void initAutoComplete() {          SharedPreferences sp = getActivity().getSharedPreferences("content", 0);          String longhistory = sp.getString("history", "没有记录");          String[] histories = longhistory.split(",");          length = histories.length;        ArrayAdapter<String> adapter;        if(length != 1){        String[] newHistories = new String[length-1];        System.arraycopy(histories, 0, newHistories, 0, length-1);                adapter = new ArrayAdapter<String>(getActivity(),          R.layout.simple_dropdown_item_1, newHistories);         }else{         adapter = new ArrayAdapter<String>(getActivity(),           R.layout.simple_dropdown_item_1, histories);         }                if (histories.length > 9) {        Editor editor = sp.edit();          //移除数据          editor.remove("history");          editor.commit();                    String[] newHistories = new String[10];              System.arraycopy(histories, 0, newHistories, 0, 10);                          String str = newHistories[0];            for (int i = 1; i < newHistories.length; i++) {            str += "," + newHistories[i];}            editor.putString("history", str).commit();            adapter = new ArrayAdapter<String>(getActivity(),                      R.layout.simple_dropdown_item_1, newHistories);         }          acTextView.setAdapter(adapter);          acTextView.setOnFocusChangeListener(new OnFocusChangeListener() {              @Override              public void onFocusChange(View v, boolean hasFocus) {                  AutoCompleteTextView view = (AutoCompleteTextView) v;                  if (hasFocus) {                      view.showDropDown();                  }              }          });      }  /** * 保存搜索内容 */private void saveHistory() {          String text = acTextView.getText().toString();          SharedPreferences sp = getActivity().getSharedPreferences("content", 0);          String longhistory = sp.getString("history", "没有记录");         if (!text.equals("") && !longhistory.contains(text + ",")) {              StringBuilder sb = new StringBuilder(longhistory);              sb.insert(0, text + ",");              sp.edit().putString("history", sb.toString()).commit();          }      }}
7、上面的基本功能已经完成了,但为了增加美观效果,在向该页面跳转时最好增加跳转效果。

overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);

in_from_left:

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate         android:fromXDelta="-100%p"         android:toXDelta="0%p"        android:duration="500" /></set>

in_from_right:

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate         android:fromXDelta="100%p"         android:toXDelta="0%p"        android:duration="500" /></set>

out_to_left:

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate         android:fromXDelta="0%p"         android:toXDelta="-100%p"        android:duration="500" /></set>

out_to_right:

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate         android:fromXDelta="0%p"         android:toXDelta="100%p"        android:duration="500" /></set>

8、MainActivity还要设置android:theme="@android:style/Theme.Translucent.NoTitleBar"
源码下载

0 0
原创粉丝点击