在ViewPagerAdapter.class
我有2个布局(whereami.xml和mapview.xml),并使用LayoutInflater来扩充instantiateItem()
内的每个视图,通常我应该设置所有内容(TextView,ImageView等根据xml)在instantiateItem()
内。但在我的情况下,我真的需要在ViewPagerActivity的onCreate()
处设置文本或背景颜色,其延伸MapActivity
那么,无论如何都要在onCreate()
中设置它们吗?
P.S。我尝试调试程序,发现该进程在instantiateItem()
方法退出之前不会调用onCreate()
。因此,当我尝试设置文本时,视图将不会创建,并且每次编程都会关闭,因为视图是空的。
ViewPagerActivity
public class ViewPagerActivity extends MapActivity {
private ViewPagerAdapter adapter;
private ViewPager pager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter = new ViewPagerAdapter(this);
pager = (ViewPager) findViewById(R.id.viewpager);
TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
pager.setAdapter(adapter);
indicator.setViewPager(pager);
//LinearLayout bgcolor = (LinearLayout)findViewById(R.id.mainlayout);
//bgcolor.setBackgroundColor(Color.Black);
//TextView text1 = (TextView)findViewById(R.id.text1);
//text1.setText("somevalue");
}
}
ViewPagerAdapter
public class ViewPagerAdapter extends PagerAdapter implements TitleProvider {
private final Context context;
private MapView mapView;
private MapController mapController;
private View view;
public ViewPagerAdapter(Context context) {
}
private static String[] titles = new String[] { "Page1", "Map" };
@Override
public Object instantiateItem(View pager, final int position) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position == 0) {
view = inflater.inflate(R.layout.whereami, null);
((ViewPager) pager).addView(view, 0);
}
if (position == 1) {
view = inflater.inflate(R.layout.my_map_activity, null);
((ViewPager) pager).addView(view, 0);
mapView = (MapView) view.findViewById(R.id.mapview);
mapController = mapView.getController();
mapController.setZoom(14);
}
return view;
}
}
whereami.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:textSize="16sp" >
</TextView>
</LinearLayout>
答案 0 :(得分:1)
如果您知道onCreate()
中TextView中的内容,为什么不通过适配器的构造函数传递它?
new ViewPagerAdapter(this, "TextToPass");
使用:
private String toDisplay;
public ViewPagerAdapter(Context context, String toDisplay) {
this.toDispay = toDisplay;
}
和
view = inflater.inflate(R.layout.whereami, null);
TextView textView = view.findViewById(R.id.text1);
textView.setText(toDisplay);