在ViewPager中动态添加视图到末尾和开头

4

一开始我的ViewPager接受列表并相应地设置视图。但是,如果到达ViewPager的末尾或开头,我想要添加更多视图到ViewPager并相应地设置位置,我该如何通过编写高效的代码来实现这一点?

这是我的Adapter

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

    // Declare Variables
    TouchImageView image;

    ImageEntity entity=list.get(position);
    final TextView text;


    inflater = (LayoutInflater)   context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.viewpager_item, container,false);

    // Locate the TextViews in viewpager_item.xml
    image = (TouchImageView) itemView.findViewById(R.id.imageView1);
    View progress=itemView.findViewById(R.id.progress);
    text=(TextView) itemView.findViewById(R.id.text);
    text.setVisibility(View.INVISIBLE);
    text.setText(entity.message);
    makeTextViewResizable(text, 1, "View more", true);
    // Capture position and set to the TextViews
    image.setImageURI(Uri.parse(Constants.FLDR_IMG+entity.localImageName));
    ContextCommons.loadMainImage(context, entity, progress, image);
    // Add viewpager_item.xml to ViewPager
    container.addView(itemView);
    return itemView;
}`

这是自定义的ViewPager
public class CustomViewPager extends ViewPager{

float mStartDragX;
float x = 0;
OnSwipeOutListener mOnSwipeOutListener;
static final String TAG="CustomViewPager";

public CustomViewPager(Context context) {
    super(context);

}

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void setOnSwipeOutListener(OnSwipeOutListener listener) {
    mOnSwipeOutListener = listener;
}

private void onSwipeOutAtStart() {
    if (mOnSwipeOutListener!=null) {
        mOnSwipeOutListener.onSwipeOutAtStart();
    }
}

private void onSwipeOutAtEnd() {
    if (mOnSwipeOutListener!=null) {
        mOnSwipeOutListener.onSwipeOutAtEnd();
    }
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch(ev.getAction() & MotionEventCompat.ACTION_MASK){
        case MotionEvent.ACTION_DOWN:
            mStartDragX = ev.getX();
            break;
    }
    return super.onInterceptTouchEvent(ev);
}

@Override
public boolean onTouchEvent(MotionEvent ev){

    if(getCurrentItem()==0 || getCurrentItem()==getAdapter().getCount()-1){
        final int action = ev.getAction();
        float x = ev.getX();
        switch(action & MotionEventCompat.ACTION_MASK){
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                if (getCurrentItem()==0 && x>mStartDragX) {

我想要更新从开始传递给视图适配器的ArrayList

                    ImageActivity.loadStart();
                }
                if (getCurrentItem()==getAdapter().getCount()-1 && x<mStartDragX){

//我想从底部更新供视图适配器使用的ArrayList

                    ImageActivity.loadEnd();
                }
                break;
        }
    }else{
        mStartDragX=0;
    }
    return super.onTouchEvent(ev);

}

public interface OnSwipeOutListener {
    void onSwipeOutAtStart();
    void onSwipeOutAtEnd();
}

我需要更新供给ViewPager的列表,以在ViewPager到达末尾或开头时添加动态视图。

我以为以下方式添加视图是错误的做法:

public static void loadStart(){
    ArrayList<ImageEntity> image = null;
    try {
        ContextCommons.loadImages(context, Constants.DIRECTION_TOP, list.get(0).id);
        image= SelectQueries.getTopLocalImagesOnId(context, list.get(0).id, Constants.DIRECTION_TOP);
        list.addAll(0,image);
    } catch (Exception e) {
        e.printStackTrace();
    }

    viewPager.getAdapter().notifyDataSetChanged();
    viewPager.setCurrentItem(image.size()-1);
}

你目前做了什么? - Pankaj Nimgade
你想要的是不理解 - jeet parmar
在你的适配器中,在getView()方法中,你可以检查是否请求了索引为0的项目,如果是,则将你的新分页项前置到数据集中并调用notifyDataSetChanged(),同样的方式也适用于末尾,如果请求了data.length位置,则追加数据并调用notifyDataSetChanged()。 - chiragjn
@chiragjn 我可以检测到结束和开始,你能具体说明一下我该如何调用notifydatasetchange()并相应地设置viewpager的位置吗? - user2582324
1个回答

1
我对Google的ViewPager示例进行了编辑,使其更简单易懂。只需点击片段上的按钮,就可以轻松地将页面增加到ViewPager中。
这是一个演示,展示如何按照您的要求通知所有更改以增加页面。您需要创建自己的自定义适配器和页面列表来保持页面及其位置的检查...
抱歉,我不会写整个代码 :(
使用以下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:gravity="center"
android:orientation="vertical"
>



<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_blank_fragment" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button" />
</LinearLayout>

它的代码是

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.Button;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends Fragment {

private Button button;
private TextView textView;
private static AddPage test;


public MyFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View layout = inflater.inflate(R.layout.fragment_my, container, false);
    button = (Button) layout.findViewById(R.id.button);
    return layout;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            test.addAnotherPage();
        }
    });
}

public void setAddPage(AddPage addPage) {
    test = addPage;
}

public interface AddPage {
    void addAnotherPage();
}

}

主活动 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=".AddingPagesTest">

<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" />

</LinearLayout>

活动代码

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.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;



public class AddingPagesTest extends AppCompatActivity {

public static int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private MyFragment set;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_adding_pages_test);

    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_adding_pages_test, menu);
    return true;
}



private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter implements MyFragment.AddPage {
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        MyFragment myFragment = new MyFragment();
        myFragment.setAddPage(this);
        return myFragment;
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public void addAnotherPage() {
        NUM_PAGES++;
        mPagerAdapter.notifyDataSetChanged();
    }
}

}

我想将2个字符串发送到片段,因为我将使用2个文本视图填充我的片段,我该如何做? - user2582324
由于您需要使每个片段都有自己的字符串,因此最好在“PagerAdapter”中进行,并将其发送到您创建的每个片段。在构造函数中拥有这些字符串,并在Fragment的“onActivityCreated”中填充它们以在UI中使用。 - Pankaj Nimgade

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接