HorizontalScrollView与ViewPager联合使用滚动屏幕以及其中涉及到的小知识

来源:互联网 发布:苹果微信录屏软件 编辑:程序博客网 时间:2024/06/08 16:06

目前正在学习android的一些相关知识,经过阿小雪同学建议,把每天学的东西写到博客上,防止学完了忘掉,前两篇都是转载的,本文是第一篇原创文章(大部分还只是把别人写好的demo代码贴上了),写的不是很专业,但也能帮我记录一些事情吧。希望大家有什么建议或问题可以直接留言,我会采纳或回复。大笑


该APP采用HorizontalScrollView与ViewPager联动达到滚动屏幕的效果,从网上找了一个完整的demo,现把详细代码贴上:

mainactivity.java

package com.example.homedome;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.view.ViewPager;import android.view.Gravity;import android.view.View;import android.widget.HorizontalScrollView;import android.widget.LinearLayout;import android.widget.TextView;import java.util.ArrayList;import java.util.List;public class MainActivity extends FragmentActivity {    private HorizontalScrollView sv;    private ViewPager vp;    private TextView tv;    private LinearLayout ly;    private FragmentAdapter mFragmentAdapter;    private CommonFragment fragment;    private List<String> tabel;    private List<TextView> tvList;    private List<Fragment> fList;    private Drawable drawableLeft;    private Drawable drawableRight;    /**     * ViewPager的当前选中页     */    private int currentIndex;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏  ,这句代码要写在setContentView()前面。       setContentView(R.layout.activity_main);        sv= (HorizontalScrollView) findViewById(R.id.sv);        vp = (ViewPager) findViewById(R.id.viewpager);        ly = (LinearLayout) findViewById(R.id.ly);        getTabel();    }    //得到标签    public void getTabel() {        tabel = new ArrayList<String>();        tvList = new ArrayList<TextView>();        /*for (int i = 0; i < 20; i++) {            tabel.add("测试" + i);        }*/        tabel.add("首页");tabel.add("电视剧");tabel.add("会员");tabel.add("综艺");        tabel.add("电影");tabel.add("动漫");tabel.add("美剧");tabel.add("韩剧");        tabel.add("自媒体");tabel.add("纪录片");tabel.add("直播");tabel.add("娱乐");        // TODO 这里记得判断获得标签的数目不为0才可以获得textview和fragment,此处数据模拟,动态获取需加判断        for (int i = 0; i < tabel.size(); i++) {            tv = new TextView(this);            tv.setText(tabel.get(i));            tv.setTextSize(16);            tv.setPadding(35, 15, 35, 15);            tv.setGravity(Gravity.CENTER);            tv.setTextColor(0xff333333);            ly.addView(tv);            tvList.add(tv);            final int finalI = i;            tv.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View v) {                    change(tvList.get(finalI));                    vp.setCurrentItem(finalI);                }            });        }        //得到fragment        getFragment(tabel.size());    }    public void getFragment(int num) {        fList = new ArrayList<Fragment>();        for (int i = 0; i < num; i++) {            fragment = new CommonFragment();            Bundle bundle = new Bundle();            bundle.putString("content", tabel.get(i));            fragment.setArguments(bundle);            fList.add(fragment);        }        mFragmentAdapter = new FragmentAdapter(                this.getSupportFragmentManager(), fList);        vp.setAdapter(mFragmentAdapter);        vp.setCurrentItem(0);                vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {            /**             * state滑动中的状态 有三种状态(0,1,2) 1:正在滑动 2:滑动完毕 0:什么都没做。             */            @Override            public void onPageScrollStateChanged(int state) {            }            /**             * position :当前页面,及你点击滑动的页面 offset:当前页面偏移的百分比             * offsetPixels:当前页面偏移的像素位置             */            @Override            public void onPageScrolled(int position, float offset,                                       int offsetPixels) {                /**                 * 利用currentIndex(当前所在页面)和position(下一个页面)以及offset来                 * 设置mTabLineIv的左边距 滑动场景:                 * 记3个页面,                 * 从左到右分别为0,1,2                 * 0->1; 1->2; 2->1; 1->0                 */            }            @Override            public void onPageSelected(int position) {                change(tvList.get(position));                sv.requestChildFocus(tvList.get(position),tvList.get(position));            }        });        change(tvList.get(0));    }    /**     * 重置颜色     */    private void change(TextView v) {        restoreTabs();      //  v.setCompoundDrawables(drawableLeft, null, drawableRight, null);      //  v.setCompoundDrawablePadding(16);        v.setTextColor(0xffda1a17);    }    private void restoreTabs() {        for (int i = 0; i <tvList.size() ; i++) {            tvList.get(i).setTextColor(0xff333333);            tvList.get(i).setCompoundDrawables(null, null, null, null);        }    }}
ViewPager具体显示的TextView内容是通过Fragment实现的,文件名:CommonFragment.java:

package com.example.homedome;import android.content.Intent;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.View.OnClickListener;import android.view.ViewGroup;import android.widget.TextView;/** * Created by zcc on 2016/5/19. */public class CommonFragment extends Fragment {    private TextView textView;    private String content;  //  @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment, container, false);        textView = (TextView) view.findViewById(R.id.tv);        content = getArguments().getString("content");        textView.setText(content+"!");                textView.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                Intent intent=new Intent();                intent.setClass(getActivity(), ImageActivity.class);                Bundle bundle = new Bundle(); //创建Bundle对象                   bundle.putString("content", content); //装入数据                   intent.putExtras(bundle); //把Bundle塞入Intent里面                   startActivity(intent);            }        });                Button btn=(Button)view.findViewById(R.id.button1);        btn.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                // TODO Auto-generated method stub                Toast.makeText(getActivity(), "点击button按钮", Toast.LENGTH_LONG).show();                                /*这里可以弹出对话框,根据自己喜好决定是否加入                            AlertDialog.Builder b=new Builder(getActivity());                b.setMessage("按钮被点击");                 b.create().show();*/                        }        });        return view;    }}

再加上一个FragmentAdapter类,实现滚动操作,文件名:FragmentAdapter.java:

package com.example.homedome;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import java.util.ArrayList;import java.util.List;/** * Created by zcc on 2016/5/19. */public class FragmentAdapter extends FragmentPagerAdapter {    List<Fragment> fragmentList = new ArrayList<Fragment>();    public FragmentAdapter(FragmentManager fm,List<Fragment> fragmentList) {        super(fm);        this.fragmentList = fragmentList;    }    @Override    public Fragment getItem(int position) {        return fragmentList.get(position);    }    @Override    public int getCount() {        return fragmentList.size();    }}


图片显示的代码,ImageActivity.java:

package com.example.homedome;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Window;import android.widget.ImageView;public class ImageActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏  ,这句代码要写在setContentView()前面。setContentView(R.layout.image);Intent intent = this.getIntent();        //获取已有的intent对象   Bundle bundle = intent.getExtras();    //获取intent里面的bundle对象   String content = bundle.getString("content");    //获取Bundle里面的字符串 ImageView welcome = new ImageView(this);if(content.equals("首页"))welcome.setImageResource(R.drawable.shouye);elsewelcome.setImageResource(R.drawable.dianshiju);setContentView(welcome);}}


主Activity的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">    <HorizontalScrollView        android:id="@+id/sv"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:scrollbars="none">        <LinearLayout            android:id="@+id/ly"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal"></LinearLayout>    </HorizontalScrollView>    <TextView        android:layout_width="match_parent"        android:layout_height="2dp"        android:background="#bdbdbd" />    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>

ViewPager中的TextView,文件名:frangemnt.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center">    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text=""        android:textSize="25dp"        android:textColor="#ccc"/>    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button" /> </LinearLayout>


图片显示的xml文件,image.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"    android:orientation="vertical" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         /></LinearLayout>



最后AndroidMenifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.homedome"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.homedome.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

至此,整个功能全部实现,效果图如下:


其中,除了滚动屏幕之外,还有几个小知识,接下来依次说明一下:

1、去掉标题栏:

在onCreate方法里加入this.requestWindowFeature(Window.FEATURE_NO_TITLE);

注意,这句代码要写在setContentView()前面才能生效;

2、在Fragment中获取Context:

直接采用getActivity()方法;

3、启动activity以及传递数据(对于我这个新手还不能默写出来):

                Intent intent=new Intent();
                intent.setClass(getActivity(), ImageActivity.class);
                Bundle bundle = new Bundle();//创建Bundle对象   
                bundle.putString("content", content);  //装入数据   
                intent.putExtras(bundle);  //把Bundle塞入Intent里面   
                startActivity(intent);

4、toast显示,虽然我这个新手现在能够默写出来,但是却犯了一个大大的低级错误:

Toast.makeText(getActivity(), "点击button按钮", Toast.LENGTH_LONG).show();

最后的.show()忘了写,效果就是怎么也toast不出来,各种找原因。。。醉醉的了,希望大家不要犯这种低级错误;

5、显示对话框:

                AlertDialog.Builder b=new Builder(getActivity());
                b.setMessage("按钮被点击");
                b.create().show();

6、在ImageView控件中加载图片:

有两种加载方式,如果图片是唯一的,那么可在xml文件中用android:src实现;

如果图片是变化的,可在java代码中实现:welcome.setImageResource(R.drawable.shouye);


0 0
原创粉丝点击