ListView转到不同的活动

时间:2011-05-30 18:38:36

标签: android listview onclick

好的,我对Android开发和编程很新。我有一个包含两个项目的listView,当用户点击它时,我希望每个项目都转到另一个Activity。这是我到目前为止的代码。

package com.pais.convert;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class list extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      String[] choose = getResources().getStringArray(R.array.list_chooser);
      setListAdapter(new ArrayAdapter<String>(this,
              android.R.layout.simple_list_item_1, choose));

      ListView lv = getListView();
      lv.setTextFilterEnabled(true);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = new Intent(this, tempConvert.class);
        intent.putExtra("KEY_SELECTED_INDEX", position);
        startActivity(intent);
    }
    }

所以这里点击它们都会转到tempConvert.class。我希望那个说“Temp”的人去tempConvert,当点击“Dist”时它会转到distConvert.class。我怎么做到这一点?

提前感谢您的帮助

3 个答案:

答案 0 :(得分:2)

在onListItemClick中,使用int position参数创建一个switch语句。然后,如果它是0,你去一个类,如果它是1,你去另一个。

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    switch(position) {
        case '0' :            
            Intent intent = new Intent(this, tempConvert.class);
            intent.putExtra("KEY_SELECTED_INDEX", position);
            startActivity(intent);
            break;
        case '1' :            
            Intent intent = new Intent(this, distConvert.class);
            intent.putExtra("KEY_SELECTED_INDEX", position);
            startActivity(intent);
            break;
    }
}

答案 1 :(得分:1)

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Intent intent = null;
    switch (position) {
    case 0:
        intent = new Intent(this, tempConvert.class);
        break;
    case 1:
        intent = new Intent(this, distConvert.class);
        break;
    }
    if (intent != null) {
        startActivity(intent);
    } else {
        // report unknown item selection
    }
}

答案 2 :(得分:0)

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = null;
switch (position) {
case 0:
    startActivity(new Intent(this, tempConvert.class));
    break;
case 1:
    startActivity(new Intent(this, distConvert.class));
    break;
}

}