开始从点击列表视图中的新活动的最佳方法 [英] Best way to start a new activity from a clicked listview

查看:82
本文介绍了开始从点击列表视图中的新活动的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,成功地显示了一个ListView为主要活动。我一直在使用,在过去几天里很多教程,试图找出启动不同的活动,从项目点击该列表视图的最佳途径。我已经看到了从switch语句由一个变量调用类,但似乎没有任何工作。我想可能是使用if语句,但我的名单超过120项。有什么建议?

I have an array that successfully shows as a listview as the main activity. I've been using many tutorials in the past few days to try to find out the best way to start different activities from items clicked on this listview. I've seen everything from switch statements to calling a class by a variable, but nothing seems to work. I would possibly use an if statement but my list is over 120 entries. Any suggestions?

推荐答案

你为什么不把类作为项目的参数?

Why don't you put the class as a parameter of the item ?

    package com.ybi;

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

    public class YbiListActivity extends ListActivity
    {
        public void onCreate(Bundle icicle)
        {
            super.onCreate(icicle);
            ClickableItem[] values = new ClickableItem[1];

                            // here you can add your label and your activity
            values[0] = new ClickableItem("Hello", YbiListActivity.class);

            ArrayAdapter<ClickableItem> adapter = new ArrayAdapter<ClickableItem>(this, android.R.layout.simple_list_item_1, values);
            setListAdapter(adapter);
        }

        @Override
        protected void onListItemClick(ListView l, View v, int position, long id)
        {
            ClickableItem item = (ClickableItem) getListAdapter().getItem(position);
            Intent intent = new Intent(YbiListActivity.this, (Class<?>) item.itemClass);
            startActivity(intent);
            Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
        }

        private class ClickableItem
        {
            public String itemLabel;
            public Object itemClass;

            public ClickableItem(String ilabel, Object iclass)
            {
                itemLabel = ilabel;
                itemClass = iclass;
            }

            @Override
            public String toString()
            {
                return itemLabel;
            }
        }
    }

这篇关于开始从点击列表视图中的新活动的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆