android gridview动态添加viewpager,动态添加和删除视图到viewpager

我做了类似的计划。希望这会对你有所帮助。在第一个活动中,可以选择四个网格数据。在下一个活动中,有一个视图寻呼机,其中包含两个必填页面。还有4个页面,它们将对应于所选的网格数据可见。

以下是mainactivty MainActivitypackage com.example.jeffy.viewpagerapp;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.database.Cursor;

import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.os.Bundle;

import android.os.Parcel;

import android.support.design.widget.FloatingActionButton;

import android.support.design.widget.Snackbar;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.Toolbar;

import android.util.Log;

import android.view.View;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.GridView;

import java.lang.reflect.Array;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

SharedPreferences pref;

SharedPreferences.Editor editor;

GridView gridView;

Button button;

private static final String DATABASE_NAME = "dbForTest.db";

private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "diary";

private static final String TITLE = "id";

private static final String BODY = "content";

DBHelper  dbHelper = new DBHelper(this);

ArrayList frags = new ArrayList();

ArrayList fragmentArray = new ArrayList();

String[] selectedData;

Boolean port1=false,port2=false,port3=false,port4=false;

int Iport1=1,Iport2=1,Iport3=1,Iport4=1,location;

// This Data show in grid ( Used by adapter )

CustomGridAdapter customGridAdapter = new           CustomGridAdapter(MainActivity.this,GRID_DATA);

static final String[ ] GRID_DATA = new String[] {

"1" ,

"2",

"3" ,

"4"

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

frags.add("TabFragment3");

frags.add("TabFragment4");

frags.add("TabFragment5");

frags.add("TabFragment6");

dbHelper = new DBHelper(this);

dbHelper.insertContact(1,0);

dbHelper.insertContact(2,0);

dbHelper.insertContact(3,0);

dbHelper.insertContact(4,0);

final Bundle selected = new Bundle();

button = (Button) findViewById(R.id.button);

pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);

editor = pref.edit();

gridView = (GridView) findViewById(R.id.gridView1);

gridView.setAdapter(customGridAdapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView> parent, View view, int position, long id) {

//view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);

location = position + 1;

if (position == 0) {

Iport1++;

Iport1 = Iport1 % 2;

if (Iport1 % 2 == 1) {

//dbHelper.updateContact(1,1);

view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);

dbHelper.updateContact(1,1);

} else {

//dbHelper.updateContact(1,0);

view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);

dbHelper.updateContact(1, 0);

}

}

if (position == 1) {

Iport2++;

Iport1 = Iport1 % 2;

if (Iport2 % 2 == 1) {

//dbHelper.updateContact(2,1);

view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);

dbHelper.updateContact(2, 1);

} else {

//dbHelper.updateContact(2,0);

view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);

dbHelper.updateContact(2,0);

}

}

if (position == 2) {

Iport3++;

Iport3 = Iport3 % 2;

if (Iport3 % 2 == 1) {

//dbHelper.updateContact(3,1);

view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);

dbHelper.updateContact(3, 1);

} else {

//dbHelper.updateContact(3,0);

view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);

dbHelper.updateContact(3, 0);

}

}

if (position == 3) {

Iport4++;

Iport4 = Iport4 % 2;

if (Iport4 % 2 == 1) {

//dbHelper.updateContact(4,1);

view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);

dbHelper.updateContact(4, 1);

} else {

//dbHelper.updateContact(4,0);

view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);

dbHelper.updateContact(4,0);

}

}

}

});

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

editor.putInt("port1", Iport1);

editor.putInt("port2", Iport2);

editor.putInt("port3", Iport3);

editor.putInt("port4", Iport4);

Intent i = new Intent(MainActivity.this,Main2Activity.class);

if(Iport1==1)

i.putExtra("3","TabFragment3");

else

i.putExtra("3", "");

if(Iport2==1)

i.putExtra("4","TabFragment4");

else

i.putExtra("4","");

if(Iport3==1)

i.putExtra("5", "TabFragment5");

else

i.putExtra("5","");

if(Iport4==1)

i.putExtra("6", "TabFragment6");

else

i.putExtra("6","");

dbHelper.updateContact(0, Iport1);

dbHelper.updateContact(1, Iport2);

dbHelper.updateContact(2, Iport3);

dbHelper.updateContact(3, Iport4);

startActivity(i);

}

});

}}

这里TabFragment1,TabFragment2等是要在viewpager上显示的片段。我没有显示布局,因为它们超出了这个项目的范围。

MainActivity将意图使用Main2Activity Main2Activitypackage com.example.jeffy.viewpagerapp;import android.content.Intent;import android.database.Cursor;import android.os.Bundle;import android.support.design.widget.CollapsingToolbarLayout;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.design.widget.TabLayout;import android.support.v4.view.ViewPager;import android.support.v4.widget.NestedScrollView;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.text.TextUtils;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.FrameLayout;import java.util.ArrayList;public class Main2Activity extends AppCompatActivity {

private ViewPager pager = null;

private PagerAdapter pagerAdapter = null;

DBHelper dbHelper;

Cursor rs;

int port1,port2,port3,port4;

//-----------------------------------------------------------------------------

@Override

public void onCreate (Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main2);

Toolbar toolbar = (Toolbar) findViewById(R.id.MyToolbar);

setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

CollapsingToolbarLayout collapsingToolbar =

(CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);

NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nested);

scrollView.setFillViewport (true);

ArrayList selectedPort = new ArrayList();

Intent intent = getIntent();

String Tab3 = intent.getStringExtra("3");

String Tab4 = intent.getStringExtra("4");

String Tab5 = intent.getStringExtra("5");

String Tab6 = intent.getStringExtra("6");

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

tabLayout.addTab(tabLayout.newTab().setText("View"));

tabLayout.addTab(tabLayout.newTab().setText("All"));

selectedPort.add("TabFragment1");

selectedPort.add("TabFragment2");

if(Tab3!=null && !TextUtils.isEmpty(Tab3))

selectedPort.add(Tab3);

if(Tab4!=null && !TextUtils.isEmpty(Tab4))

selectedPort.add(Tab4);

if(Tab5!=null && !TextUtils.isEmpty(Tab5))

selectedPort.add(Tab5);

if(Tab6!=null && !TextUtils.isEmpty(Tab6))

selectedPort.add(Tab6);

dbHelper = new DBHelper(this);//        rs=dbHelper.getData(1);//        port1 = rs.getInt(rs.getColumnIndex("id"));        rs=dbHelper.getData(2);//        port2 = rs.getInt(rs.getColumnIndex("id"));        rs=dbHelper.getData(3);//        port3 = rs.getInt(rs.getColumnIndex("id"));        rs=dbHelper.getData(4);//        port4 = rs.getInt(rs.getColumnIndex("id"));

Log.i(">>>>>>>>>>>>>>", "port 1" + port1 + "port 2" + port2 + "port 3" + port3 + "port 4" + port4);

if(Tab3!=null && !TextUtils.isEmpty(Tab3))

tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));

if(Tab3!=null && !TextUtils.isEmpty(Tab4))

tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));

if(Tab3!=null && !TextUtils.isEmpty(Tab5))

tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));

if(Tab3!=null && !TextUtils.isEmpty(Tab6))

tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);

final PagerAdapter adapter = new PagerAdapter

(getSupportFragmentManager(), tabLayout.getTabCount(), selectedPort);

viewPager.setAdapter(adapter);

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

@Override

public void onTabSelected(TabLayout.Tab tab) {

viewPager.setCurrentItem(tab.getPosition());

}

@Override

public void onTabUnselected(TabLayout.Tab tab) {

}

@Override

public void onTabReselected(TabLayout.Tab tab) {

}

});//        setContentView(R.layout.activity_main2);//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//        setSupportActionBar(toolbar);//        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);//        tabLayout.addTab(tabLayout.newTab().setText("View"));//        tabLayout.addTab(tabLayout.newTab().setText("All"));//        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));//        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));//        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));//        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);}

}

ViewPagerAdapter Viewpageradapter.classpackage com.example.jeffy.viewpagerapp;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentStatePagerAdapter;import android.support.v4.view.ViewPager;import android.view.View;import android.view.ViewGroup;import java.util.ArrayList;import java.util.List;/**

* Created by Jeffy on 25-01-2016.

*/public class PagerAdapter extends FragmentStatePagerAdapter {

int mNumOfTabs;

List values;

public PagerAdapter(FragmentManager fm, int NumOfTabs, List Port) {

super(fm);

this.mNumOfTabs = NumOfTabs;

this.values= Port;

}

@Override

public Fragment getItem(int position) {

String fragmentName = values.get(position);

Class> clazz = null;

Object fragment = null;

try {

clazz = Class.forName("com.example.jeffy.viewpagerapp."+fragmentName);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

try {

fragment = clazz.newInstance();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

}

return (Fragment) fragment;

}

@Override

public int getCount() {

return values.size();

}}

main2activity acticity_main2.xml的布局

xmlns:app="http://schemas.android.com/apk/res-auto"

android:id="@+id/main_content"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:fitsSystemWindows="true">

android:id="@+id/MyAppbar"

android:layout_width="match_parent"

android:layout_height="256dp"

android:fitsSystemWindows="true">

android:id="@+id/collapse_toolbar"

android:layout_width="match_parent"

android:layout_height="match_parent"

app:layout_scrollFlags="scroll|exitUntilCollapsed"

android:background="@color/material_deep_teal_500"

android:fitsSystemWindows="true">

android:id="@+id/bgheader"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="centerCrop"

android:fitsSystemWindows="true"

android:background="@drawable/screen"

app:layout_collapseMode="pin" />

android:id="@+id/MyToolbar"

android:layout_width="match_parent"

android:layout_height="?attr/actionBarSize"

app:layout_collapseMode="parallax" />

android:layout_width="match_parent"

android:id="@+id/nested"

android:layout_height="match_parent"

android:layout_gravity="fill_vertical"

app:layout_behavior="@string/appbar_scrolling_view_behavior">

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical">

android:id="@+id/tab_layout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@+id/MyToolbar"

android:background="?attr/colorPrimary"

android:elevation="6dp"

android:minHeight="?attr/actionBarSize"

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/view_pager"

android:layout_width="match_parent"

android:layout_height="match_parent" >

Mainactivity layout

activity_main.xml        <?xml  version="1.0" encoding="utf-8"?>

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

app:layout_behavior="@string/appbar_scrolling_view_behavior"

tools:context="com.example.jeffy.viewpagerapp.MainActivity"

tools:showIn="@layout/activity_main">

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical">

android:id="@+id/gridView1"

android:numColumns="2"

android:gravity="center"

android:columnWidth="100dp"

android:stretchMode="columnWidth"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="SAVE"

android:id="@+id/button" />

希望这会有所帮助...如果这对你有所帮助,请点击按钮

PageGridViewViewPager GridView组合控件实现网格布局分页效果大多数app首页界面一般貌似可以滑动切换上下页的网格布局,这种效果用得挺多,可惜Android原生是没有这样的控件的。在工作中,我也用到过几次。但每次实现都是按ctrl A C V,代码写得也不优雅,就是再次重新复制粘贴,也避免不了看上几眼,修改修改,特别不爽快。每次吐槽的同时在想,下次我要再用到这种效果,我就将这些代码关进小黑屋。拒绝再写重复代码,虽然大多数只是按ctrl A C V。这次,我终于要将自己吐槽时的想法付之行动的。再写之前,为了避免重复造轮子。在网上搜了好多次,嗯,没有意外,我还是没有发现到惊喜。那就开始行动了。这种效果用ViewPager GridView实现,那我就叫它PageGridView吧(其实名字我也想了好久)有用的话,star一下也是不错的!!!PageGridView 特点可自由定制Item布局无需写adapter适配器,直接调用setData()方法填充数据只需实体类继承ItemModel即可可显示本地图、网络图、资源ID图标,由开发者实现动态计算PageGridView高度,不需要在布局里面写固定高度可重复setData()方法刷新数据PageGridView自定义属性属性名说明默认值pageSize每页大小8numColumns列数4isShowIndicator是否显示指示器trueselectedIndicator选中指示点资源IDR.mipmap.ic_dot_selectedunSelectedIndicator未选中指示点资源IDR.mipmap.ic_dot_normalindicatorGravity指示器位置centerindicatorPaddingLeft指示器左内边距0pxindicatorPaddingRight指示器右内边距0pxindicatorPaddingTop指示器上内边距0pxindicatorPaddingBottom指示器下内边距0pxindicatorPadding指示器内边距0pxindicatorBackground指示器背景颜色Color.WHITEitemViewItem布局R.layout.item_view约定规则Item布局必须给定具体高度,默认itemView布局的高度为@dimen/item_height=80dpItem布局 TextView的id 为R.id.tv_item_nameItem布局 ImageView的id 为R.id.iv_item_iconItem默认点击效果R.drawable.selector_item_view_bgItem点击颜色值:R.color.item_view_selected_colorItem背景颜色值:R.color.item_view_normal_color一行四列效果图两行四列效果图自定义Item布局效果图PageGridView使用Gradle 依赖库implementation 'com.wihaohao:PageGridView:1.0.1'默认布局一般默认参数即可满足需求<com.wihaohao.PageGridView           android:id="@ id/vp_grid_view"           android:layout_width="match_parent"           android:layout_height="wrap_content"           />一行4列的布局  <com.wihaohao.PageGridView           android:id="@ id/vp_grid_view"           android:layout_width="match_parent"           android:layout_height="wrap_content"           app:numColumns="4"           app:pageSize="4"           app:selectedIndicator="@mipmap/ic_dot_selected"           app:unSelectedIndicator="@mipmap/ic_dot_normal"           app:isShowIndicator="true"           />两行4列的布局    <com.wihaohao.PageGridView         android:id="@ id/vp_grid_view"         android:layout_width="match_parent"         android:layout_height="wrap_content"         app:indicatorPadding="10dp"         app:isShowIndicator="true"         app:itemView="@layout/my_item_view"         app:numColumns="4"         app:pageSize="8"         app:selectedIndicator="@mipmap/ic_dot_selected"         app:unSelectedIndicator="@mipmap/ic_dot_normal" />自定义Item布局 <com.wihaohao.PageGridView                 android:id="@ id/p_grid_view2"         android:layout_width="match_parent"         android:layout_height="wrap_content"         app:indicatorGravity="right"         app:indicatorPaddingRight="@dimen/padding_10"         app:isShowIndicator="true"         app:itemView="@layout/item_custom"         app:indicatorBackground="@color/colorPrimary"         app:numColumns="5"         app:pageSize="5"/>ItemModelpublic abstract static class ItemModel {                 /**                  * 返回item名字                  *                  * @return                  */         protected abstract String getItemName();         /**                  * 设置图标                  *                  * @param imageView         */         protected abstract void setIcon(ImageView imageView);          /**                  * 特殊需求,重写该方法,设置item                  *                  * @param itemView                  */         protected void setItemView(View itemView) {         }     }Model继承VpGridView.ItemModel 为item赋值设置图标public abstract static class ItemModel {                 /**                  * 返回item名字                  *                  * @return         */         protected abstract String getItemName();                 /**                  * 设置图标                  *                  * @param imageView                  */         protected abstract void setIcon(ImageView imageView);                 /**                  * 特殊需求,重写该方法,设置item                  *                  * @param itemView                  */         protected void setItemView(View itemView) {         }     }继承VpGridView.ItemModel 设置ItemViewpublic class MyIconModel extends PageGridView.ItemModel {     private String name;         private int iconId;         public String getName() {             return name;     }         public void setName(String name) {             this.name = name;     }         public int getIconId() {             return iconId;     }         public void setIconId(int iconId) {             this.iconId = iconId;     }         public MyIconModel(String name, int iconId) {             this.name = name;             this.iconId = iconId;     }         @Override     protected String getItemName() {             return name;     }         @Override     protected void setIcon(ImageView imageView) {         imageView.setImageResource(iconId);     } }PageGridView的使用public class MainActivity extends AppCompatActivity {     List<MyIconModel> mList;         List<CustomModel> mList2;         private PageGridView<MyIconModel> mPageGridView;         private PageGridView<CustomModel> mPageGridView2;         @Override     protected void onCreate(Bundle savedInstanceState) {                 super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         mPageGridView =findViewById(R.id.vp_grid_view);         initData();         mPageGridView.setData(mList);         mPageGridView.setOnItemClickListener(new PageGridView.OnItemClickListener() {            @Override             public void onItemClick(int position) {                Toast.makeText(MainActivity.this,position "",Toast.LENGTH_SHORT).show();             }         });        //自定义item         mPageGridView2=findViewById(R.id.p_grid_view2);         mPageGridView2.setData(mList2);     }         private void initData() {         mList=new ArrayList<>();         mList2=new ArrayList<>();                 for(int i=0;i<30;i ){             mList.add(new MyIconModel("测试" i,R.mipmap.ic_launcher));             mList2.add(new CustomModel("标题" i));         }     } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值