gpt4 book ai didi

android - 如何在 ViewPager 中添加多个 TextView 或其他 View

转载 作者:行者123 更新时间:2023-11-29 19:21:57 29 4
gpt4 key购买 nike

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

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

这是我的Fragment.java

public class YaklasanlarFragment extends Fragment {

CircularProgressBar c3;

ViewPager viewPager = null;
String bilgiler[] = {"34 YNS 54","54 E 2554"};
String tipler[] = {"Muayene Tarihi","Sigorta Tarihi"};

public YaklasanlarFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.activity_yaklasanlar_fragment, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
viewPager.setAdapter(new MyAdapter());
return view;
}

class MyAdapter extends PagerAdapter{

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

@Override
public Object instantiateItem(View container, int position)
{
TextView plaka = new TextView(getActivity());
plaka.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
plaka.setText(bilgiler[position]);
((ViewPager) container).addView(plaka, 0);
return plaka;


}
}

最佳答案

请参阅下面的代码,说明我们如何将 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;
}
}

关于android - 如何在 ViewPager 中添加多个 TextView 或其他 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42245746/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com