android list view onclick to next activity

时间:2016-02-07 09:58:32

标签: android

当我点击列表视图上的项目时,我想进入下一个活动,下面是我的代码(当我点击sub1时我需要转到sub1.class)请帮帮我

package com.example.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.vikram.om.R;

    public class fragment2 extends Fragment{
        ListView listView;
       ArrayAdapter<String> adapter;
       String[] sem_II = {"sub1","sub2","sub3"};
       @Nullable
       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.fragment2_layout, container, false);

        listView = (ListView) v.findViewById(R.id.list_View);
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, sem_II);
        listView.setAdapter(adapter);
        return v;
    }
}

1 个答案:

答案 0 :(得分:3)

在您定义列表视图的Fragment中,您可以编写

listview.setOnItemClickListener(new OnItemClickListener(){

   @Override
   public void onItemClick(AdapterView<?>adapter,View v, int position){

      ItemClicked item = adapter.getItemAtPosition(position);

      Intent intent = new Intent(getActivity(),destinationActivity.class);
      //based on item add info to intent
      startActivity(intent);

   }
});

在您的适配器中getItem编写

public ItemClicked getItem(int position){

    return items.get(position);
}

根据this link