如何在ViewPager中添加许多TextView或其他视图

时间:2017-02-15 09:44:52

标签: android android-viewpager

我想在我的ViewPager中添加2个或更多TextView。但我不知道这个问题。它太复杂了。

来自 tipler 数组的第二个TextView资源。

这是我的 Fragment.java

list_ppl_link =  driver.find_element_by_xpath('//div[@class="pro-tease"]//div[@class="pro-tease even"]')   

1 个答案:

答案 0 :(得分:2)

请参阅下面的代码,说明我们如何将TextView动态添加到ViewPager。以下是Adapter类,您需要将Adapter设置为ViewPager

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CustomPagerAdapter extends PagerAdapter {

    String bilgiler[] = {"34 YNS 54","54 E 2554"};
    String tipler[] = {"Muayene Tarihi","Sigorta Tarihi"};
    private Context mContext;

    public CustomPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        //if Length of both array's  (bilgiler and tipler) Always remains same then we can do code like below.
    String modelObject = bilgiler[position] + tipler[position];
    LayoutInflater inflater = LayoutInflater.from(mContext);
    LinearLayout linearLayout = new LinearLayout(mContext);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
    TextView textView = new TextView(linearLayout.getContext());
    textView.setText(modelObject);
    linearLayout.addView(textView);
    Button button = new Button(linearLayout.getContext());
    linearLayout.addView(button);
    collection.addView(linearLayout);
    return linearLayout;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return bilgiler.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}