我有一个有效的应用程序。现在我想修改它以使用ViewPager。我的意思是,我已经定义了一个新活动,我想使用ViewPager在活动之间滑动。为了做到这一点,我将原始活动转换为片段。这是原始(简化)代码
public class ListViewImagesActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Fish> image_details = populateList();
final ListView lv1 = (ListView) findViewById(R.id.listV_main);
final ItemListBaseAdapter ilba = new ItemListBaseAdapter(this, image_details);
lv1.setAdapter(ilba);
lv1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
Fish obj_itemDetails = (Fish) o;
Intent intent = new Intent(ListViewImagesActivity.this, DisplayFishDetailActivity.class);
startActivity(intent);
}
});
}
}
我已经通过以下方式修改了代码。
import android.support.v4.app.Fragment;
public class ListViewImagesActivity extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
return inflater.inflate(R.layout.activity_display_fish_detail, container, false);
}
@Override
public void onStart() {
super.onStart();
ArrayList<Fish> image_details = populateList();
final ListView lv1 = (ListView) getView().findViewById(R.id.pager);
final ItemListBaseAdapter ilba = new ItemListBaseAdapter(getActivity(), image_details);
lv1.setAdapter(ilba);
lv1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
Fish obj_itemDetails = (Fish) o;
Intent intent = new Intent(getActivity(), DisplayFishDetailActivity.class);
startActivity(intent);
}
});
}
现在,适配器ItemListBaseAdapter使用getActivity()而不是this接收上下文(实际上我不确定这是否正确)。运行应用程序时,我在lv1.setAdapter(ilba)处遇到空指针异常。
有什么提示吗?
提前致谢