0
在ViewPagerAdapter.class
我有2個佈局(whereami.xml和mapview.xml),並使用LayoutInflater來爲每個視圖充氣instantiateItem()
,通常我應該在instantiateItem()
內設置所有內容(TextView,ImageView等等)。但對我來說,我真的需要在ViewPagerActivity的onCreate()
到的setText或背景顏色延伸MapActivity
可以在ViewPagerAdapter之外設置文字或背景顏色嗎?
是這樣,反正有沒有設定他們onCreate()
?
P.S.我嘗試調試程序,發現該進程在調出onCreate()
方法之前不會調用instantiateItem()
。所以,視圖將不會創建,並且每當我嘗試設置Text時由於視圖爲空而導致程序關閉。
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>