如何从可点击的ListView中查看ViewFlipper的特定子项?

时间:2016-11-06 17:47:58

标签: android listview viewflipper

我有两项活动,其中一项(FirstActivity)有一个可点击的ListView,其中有两项item1item2。另一个(SecondActivityViewFlipper有两个子布局layout1layout2,我想通过点击layout1item1 ListView,我的问题是如何做到这一点?我到目前为止已经做了

showPoemListLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

           if(position == 0){
               viewFlipper.setDisplayedChild(0);
               viewFlipper.setDisplayedChild(viewFlipper.indexOfChild(findViewById(R.id.anamikaSV)));


           }

       }
   });

但它根本不起作用:(点击item1

后出现空指针异常

1 个答案:

答案 0 :(得分:0)

你正在获得NPE,因为你还没有开始SecondActivity。你可以这样做

在FirstActivity中

showPoemListLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


        if(position == 0){
            Intent intent = new Intent(this, SecondActivity.class);
            intent.putExtra("POSITION_CLICKED",0);
            startActivity(intent);
        }

    }
});

然后在SecondActivity的OnCreate中,在setContentView来电之后,执行此操作

ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.your_viewflipper_id);
Intent intent = getIntent();
int POSITION_CLICKED = intent.getIntExtra("POSITION_CLICKED",0);
viewFlipper.setDisplayedChild(POSITION_CLICKED);

只需将R.id.your_viewflipper_id替换为ViewFlipper的ID。

Developer guide on starting a new Activity