如何在选择listItem时启动新活动?

时间:2015-07-28 17:29:57

标签: java android android-intent

我的Android应用程序的主要活动页面主要是一个listView,点击该列表中的项目我想要一个新的活动开始。我已经在MainActivity类的onCreate方法中创建了intent,如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
    ListView lv = (ListView) findViewById(R.id.listview);
    lv.setAdapter(adapter);   

    final MainActivity context  = this;

    lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
            Intent myIntent = new Intent(context, SubActivity.class);
            myIntent.addFlags(position); //Optional parameters
            context.startActivity(myIntent);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}

我的新活动课程如下:

public class SubActivity extends MainActivity{

ArrayList<String> sublist = new ArrayList<String>();
ArrayAdapter<String> subadapter;

ArrayList<ArrayList<String>> corrReceipts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    int position = intent.getFlags(); //this gives me the index of the receipt

    corrReceipts = super.addedReceipts;

    TextView tv = new TextView(this);
    tv.setText("Hello");


    subadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sublist);
    ListView slv = (ListView) findViewById(R.id.sublistview);
    slv.setAdapter(subadapter); 


    sublist.addAll(corrReceipts.get(position));
    subadapter.notifyDataSetChanged();

    setContentView(slv);

}

}

我的subActivity类扩展了MainActivity,因为它需要访问一个从中获取信息的数组。当我运行此代码,并单击列表项时,没有任何反应。对我做错的任何帮助都会有很大的帮助!

1 个答案:

答案 0 :(得分:1)

您想要的只是ItemClickListener而不是ItemSelectedListener

lv.setOnItemClickListener(new OnItemClickListener()
{
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
    { 
        Intent myIntent = new Intent(context, SubActivity.class);
        myIntent.addFlags(position); //Optional parameters
        context.startActivity(myIntent);
    }
});

OnItemSelectedListener用于Spinners,OnItemClickListener用于ListView。