欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Androi开发的一些总结

程序员文章站 2022-05-07 12:08:36
...

关于xml文件的一些属性

  • layout_margin:使用该属性布局和父布局的距离值
  • padding:使用该属性的布局中内容和该布局的距离
  • 控件+view(权重设置为1)+控件+view(权重设置为1)+控件,可以使三个控件均匀分布
  • gravity:比如:TextView中文字位于该TextView的位置,一般设置为center

viewpager基本用法

  • 轮播图片:xml中用viewpager控件,表示轮播的位置。handler消息机制实现自动轮播,目前理解为过一段时间发送一个消息,让android自己执行动作。设置适配器,设置监听页面变化的方法。
private Handler handler=new Handler(){
    public void handleMessage(android.os.Message msg) {
        int currentItem = vpRiskImage.getCurrentItem();
        int newCurrentItem = currentItem + 1;
        vpRiskImage.setCurrentItem(newCurrentItem);
        sendEmptyMessageDelayed(0, 3000);
    }
};//handler自动翻页
public void initViewPager(){
    int current;
    for(current=0;current<images.length;current++){
        imageList.add(images[current]);
    }//添加图片资源
    vpRiskImage.setAdapter(new MyPagerAdapter(this,imageList));//设置适配器
    vpRiskImage.setCurrentItem(1000);//设置当前页的位置
    //调用页面翻页监听函数
    vpRiskImage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //position:点击滑动的界面位置(viewpager页面的位置为:0,1,2...)
            //positionOffset:滑动页面占整个页面的百分比
            //positionOffsetPixels:屏幕像素位置
        }
        @Override
        public void onPageSelected(int position) {
            //position:滑动完成后页面的位置(0,1,2),即当前页面的位置编号
        }
        @Override
        public void onPageScrollStateChanged(int state) {
            //state:三个值代表当前页面的三个状态
            //0:代表页面静止 1:代表页面开始滑动  2:代表手指从页面上抬起
        }
    });
    vpRiskImage.addOnPageChangeListener(new PageIndicator(getContext(), dotHorizontal,4));//调用重写的页面翻页监听函数,实现小圆点指示器;第二个参数为小圆点所在的布局
    //4代表小圆点个数
    handler.sendEmptyMessageDelayed(0,3000);//目前理解为页面翻页的间隔时间
    vpRiskImage.setOnTouchListener(new View.OnTouchListener(){//调用页面触碰函数
        public boolean onTouch(View v,MotionEvent event){
            int action=event.getAction();
            switch(action){
                case MotionEvent.ACTION_DOWN:{//手指按下,移除消息发送
                    handler.removeCallbacksAndMessages(null);
                    break;
                }
                case MotionEvent.ACTION_UP:{//手指抬起,发送紧急消息,自动翻页
                    handler.sendEmptyMessageDelayed(0,3000);
                    break;
                }
            }
            return false;
        }
    });
}
/*小圆点指示器*/
public class PageIndicator implements ViewPager.OnPageChangeListener {
    private int mPageCount;//页数
    private List<ImageView> mImgList;//保存img总个数
    private int img_select;
    private int img_unSelect;
    public PageIndicator(Context context, LinearLayout linearLayout, int pageCount) {
        this.mPageCount = pageCount;
        mImgList = new ArrayList<>();
        img_select = R.drawable.dot_select;
        img_unSelect = R.drawable.dot_unselect;
        final int imgSize = 25;
        for (int i = 0; i < mPageCount; i++) {
            ImageView imageView = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            //为小圆点左右添加间距
            params.leftMargin = 10;
            params.rightMargin = 10;
            //给小圆点一个默认大小
            params.height = imgSize;
            params.width = imgSize;
            if (i == 0) {
                imageView.setBackgroundResource(img_select);
            } else {
                imageView.setBackgroundResource(img_unSelect);
            }
            //为LinearLayout添加ImageView
            linearLayout.addView(imageView, params);
            mImgList.add(imageView);
        }
    }
  • 轮播三个TextView:轮播机制不变,把数据传给适配器,在适配器的instantiateItem方法中根据position设置textview内容,对应三个xml文件。适配器继承PagerAdapter.

  • 轮播三个fragment:设置轮播机制不变,只实现了手去滑动页面改变的效果。在onCreat中创建好三个fragment的集合,传给适配器,让适配器来加载fragment。这样fragment中可以展示任何想要的内容。还有一个思路是(但是这个思路没去做):把数据传给适配器,适配器根据position来设置三个fragment的内容。viewpagerfragment连用,适配器继承FragmentPagerAdapter.

    public void initViewPager(){
        intitFragment();//创建三个fragment实现
        MyFragmentPagerAdapter adapter =new MyFragmentPagerAdapter(getSupportFragmentManager(),fragmentList);//创建适配器,传参(fragment)
        vpProjectQualityList.setAdapter(adapter);
        vpProjectQualityList.setCurrentItem(0);//设置界面打开的初始页面位置:0
        vpProjectQualityList.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //position:点击滑动的界面位置(viewpager页面的位置为:0,1,2...)
                //positionOffset:滑动页面占整个页面的百分比
                //positionOffsetPixels:屏幕像素位置
            }
    
            @Override
            public void onPageSelected(int position) {
                //position:滑动完成后页面的位置(0,1,2),即当前页面的位置编号
            }
    
            @Override
            public void onPageScrollStateChanged(int state) {
                //state:三个值代表当前页面的三个状态
                //0:代表页面静止 1:代表页面开始滑动  2:代表手指从页面上抬起
            }
        });//viewpager监听页面的滑动改变
        vpProjectQualityList.addOnPageChangeListener(new PageIndicator(getContext(), dotHorizontal,3));//小圆点指示器的实现
    }
    //向三个fragment传数据,创建fragment
    public void intitFragment(){
        //根据评级分开数据
        for(int i=0;i<lineQualityData.size();i++){
            switch(lineQualityData.get(i).getLevel()){
                case "优":
                    ampleData.add(lineQualityData.get(i));
                    break;
                case "中":
                    mediumData.add(lineQualityData.get(i));
                    break;
                case "差":
                    badData.add(lineQualityData.get(i));
                    break;
            }
        }
        //ampleListFragment
        Bundle bundle=new Bundle();
        List<LineQualityEntity>ampleData01=new ArrayList<>(ampleData);
        bundle.putParcelableArrayList("ampleData", (ArrayList<? extends Parcelable>)ampleData01);
        ampleListFragment.setArguments(bundle);
        fragmentList.add(ampleListFragment);
        //mediumListFragment
        Bundle bundle02=new Bundle();
        List<LineQualityEntity>mediumData01=new ArrayList<>(mediumData);
        bundle02.putParcelableArrayList("mediumData", (ArrayList<? extends Parcelable>)mediumData01);
        mediumListFragment.setArguments(bundle02);
        fragmentList.add(mediumListFragment);
        //badListFragment
        Bundle bundle01=new Bundle();
        List<LineQualityEntity>badData01=new ArrayList<>(badData);
        bundle01.putParcelableArrayList("badData", (ArrayList<? extends Parcelable>)badData01);
        badListFragment.setArguments(bundle01);
        fragmentList.add(badListFragment);
    }
    public class PageIndicator implements ViewPager.OnPageChangeListener {
        private int mPageCount;//页数
        private List<ImageView> mImgList;//保存img总个数
        private int img_select;
        private int img_unSelect;
        //自定义构造器,完成小圆点相关初始化工作
        public PageIndicator(Context context, LinearLayout linearLayout, int pageCount) {
            this.mPageCount = pageCount;
            mImgList = new ArrayList<>();
            img_select = R.drawable.dot_indicator_set;
            img_unSelect = R.drawable.dot_indicator_unset;
            final int imgSize = 25;
            for (int i = 0; i < mPageCount; i++) {
                ImageView imageView = new ImageView(context);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                //为小圆点左右添加间距
                params.leftMargin = 10;
                params.rightMargin = 10;
                //给小圆点一个默认大小
                params.height = imgSize;
                params.width = imgSize;
                if (i == 0) {
                    imageView.setBackgroundResource(img_select);
                } else {
                    imageView.setBackgroundResource(img_unSelect);
                }
                //为LinearLayout添加ImageView
                linearLayout.addView(imageView, params);
                mImgList.add(imageView);
            }
        }
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
    
        @Override
        public void onPageSelected(int position) {
            //position为当前页面的编号,for循环确定当前页面的编号,同时设置小圆点的背景
            for (int i = 0; i < mPageCount; i++) {
                //选中的页面改变小圆点为选中状态,反之为未选中
                if ((position % mPageCount) == i) {
                    (mImgList.get(i)).setBackgroundResource(img_select);
                } else {
                    (mImgList.get(i)).setBackgroundResource(img_unSelect);
                }
            }
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {}
    }//小圆点指示器的具体实现,创造实现ViewPager.OnPageChangeListener的类
    

    适配器代码:

    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
      public List<Fragment> fragmentList;
    
      public MyFragmentPagerAdapter(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();
      }
    

}


### 两个`Activity`交互的效果

- 实现效果见下图:

![在这里插入图片描述](https://img-blog.csdnimg.cn/2019030815105938.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2NzUxNDg3,size_16,color_FFFFFF,t_70)

- 在`A`的`onCreat`中重写**`onActivityResult`**,用于处理`B`传来的数据。点击跳转函数中添加**`startActivityForResult`**方法,实现调转到`B`的作用。用**`Bundle`**接受数据。

```java
//跳转子系统(B)
@OnClick(R.id.layout_Subsystem)
public void onViewClicked() {
    Intent intent = new Intent(getContext(),SystemListActivity.class);
    startActivityForResult(intent,22);
}
//子系统销毁后调用,接受处理子系统返回的数据,刷新列表
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode,resultCode,data);
    if(requestCode==22&&resultCode==10){
    Bundle bundle = data.getExtras();
    List <StatusData> subsystemData = (List<StatusData>) bundle.getSerializable("subsystemData");
    parameterListAdapter = new ProDetailQualityAdapter(getApplicationContext(), subsystemData, maxDatas_constant);
        rvParameterListTable.setAdapter(parameterListAdapter);
    }

BonCreat中,点击事件的跳转函数中,用putExtra传递数据,并用**setResult方法**

@Override
public void onItemClick(int position) {
    List <StatusData>subsystemData=new ArrayList<>(data.get(position).getStatusData());//标准化处理,构造成想要传递的数据类型
    Intent intent = new Intent(getContext(),ParameterListActivity.class);
    intent.putExtra("subsystemData",(Serializable)subsystemData);
    setResult(10,intent);
    finish();
}

交互传参问题

  • 两个Activity之间传递List,发送方用putExtra,接受方用Bundle(中间桥梁,把数据捆起来)

    注意发送前的数据“标准化”处理。List的类要实现Serializable(不然会出现序列化问题)

    //发送方
    List <StatusData>subsystemData=new ArrayList<>(data.get(position).getStatusData());
                    Intent intent = new Intent(getContext(),ParameterListActivity.class);
                    intent.putExtra("subsystemData",(Serializable)subsystemData);
    //接收方
    Bundle bundle = data.getExtras();
    List <StatusData> subsystemData = (List<StatusData>) bundle.getSerializable("subsystemData");//subsystemData是数据的代号
    
  • Activityfragment传参,List的类要实现Parcelable(不然会出现序列化问题)

    //Activity中
    Bundle bundle=new Bundle();//用Bundle捆绑数据
    List<LineQualityEntity>ampleData01=new ArrayList<>(ampleData);
    bundle.putParcelableArrayList("ampleData", (ArrayList<? extends Parcelable>)ampleData01);//用putParcelableArrayList发送数据,ampleData是数据代号
    ampleListFragment.setArguments(bundle);//要接受的fragment引用setArguments方法
    //Fragment中
    Bundle bundle01 = getArguments();//Bundle,getArguments获得数据
    ampleData=bundle01.getParcelableArrayList("ampleData");//调用getParcelableArrayList得到数据
    

RecycleView的基本使用

  • activity中的相关代码:
 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        };//设置布局管理器,对应xml文件中有recycleview的插件
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);//设置item排列的方向为竖向
        rvSystemlistTable.setLayoutManager(layoutManager);
        //设置分割线,分割线是自己定义的drawable的xml文件
        DividerItemDecoration decoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        decoration.setDrawable(getResources().getDrawable(R.drawable.divider,null));
        rvSystemlistTable.addItemDecoration(decoration);
        //rvSystemlistTable.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mPresenter.getSystemListData();
        unbinder = ButterKnife.bind(this);
    }
  • 适配器,继承RecyclerView.Adapter
public class SystemListAdapter extends RecyclerView.Adapter<SystemListAdapter.MyViewHolder> {
    private Context context;
    private List <ParameterListEntity>system_name;
    private LayoutInflater inflate;
    private OnItemClickListener mOnItemClickListener;

    public SystemListAdapter(Context context,List <ParameterListEntity> system_name ){
        this.context=context;
        this.system_name=system_name;
        this.inflate=LayoutInflater.from(context);
    }
    public interface OnItemClickListener{
        void onItemClick( int position);
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
         mOnItemClickListener=onItemClickListener;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(inflate.inflate(R.layout.item_systemlist,parent,false));
    }
    @Override
    public void onBindViewHolder( MyViewHolder holder, final int position) {
        holder.item_SystemListView.setText(system_name.get(position).getSunSystem());
        //给每行设置监听
        if(mOnItemClickListener!=null){
            holder.item_SystemListView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onItemClick(position);
                }
            });

        }
    }




    @Override
    public int getItemCount() {
        return system_name.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        public TextView item_SystemListView;
        public MyViewHolder(View itemView) {
            super(itemView);
            item_SystemListView= itemView.findViewById(R.id.tv_systemlist);
        }
    }
}
相关标签: 个人总结