如何在列表视图中创建活动

时间:2010-09-24 23:56:51

标签: java android eclipse

我在选项卡中创建了一个列表视图,其中包含一个团队列表。我想创建一个活动,当点击它转到另一个类时,我想用这个列表中的20个项目执行此操作。到目前为止我的代码是:

public class ll2 extends ListActivity {

    static final String[] teams = new String[]{"Accrington Stanley",
            "Aldershot", "Barnet", "Bradford City", "Burton Albion",
            "Bury", "Cheltenham Town", "Chesterfield", "Crewe Alexandra"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final String[] TEAMS = getResources().getStringArray(R.array.twoteams_array);
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, TEAMS));


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

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                        Toast.LENGTH_SHORT).show();


                Intent intent;

                intent = new Intent().setClass(this, Bradford.class);


            }
        });
    }

}

我已阅读了一些教程,但他们没有提到如何点击可点击的列表视图。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您可能希望覆盖ListActivity中的onListItemClick方法。根据位置,您将构建一个适当的意图。

@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
    if (position == appropriate_condition) {
        Intent intent = new Intent(this, Bradford.class);
        startActivity(intent);
    }
}

如果您需要访问与该项目相关联的数据,documentation会提供以下建议:

  

如果子类需要访问与所选项目关联的数据,则可以调用getListView().getItemAtPosition(position)

答案 1 :(得分:0)

listView = (ListView) findViewById(R.id.listView1);

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
        intent.putExtra("ID", ""+id);
        startActivity(intent);
        finish();
    }
});