【问题标题】:Each ListView item opens layout with different text每个 ListView 项目打开布局与不同的文本
【发布时间】:2015-08-13 21:30:52
【问题描述】:

如果我需要为每个 ListView 项目打开具有不同文本的布局并且我有很多 ListView 项目(大约 50 个),我的 onClickListener 应该是什么样子?我需要为每个新项目创建新的活动或布局文件吗?是否可以对所有项目使用一项活动? 这是我的 MainActivity.java:

public class MainActivity extends Activity {
    // ListView
    private ListView listView;

    // Adapter
    ArrayAdapter<String> adapter;

    String items [];

    // ArrayList
    ArrayList<HashMap<String, String>> productList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //ListView data in res/values/arrays.xml
        items =getResources().getStringArray(R.array.items);


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

        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listItem, items);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

                /* 
                I know that I can put here I can put something like this:

                case 0 :Intent appInfo = new Intent(About.this, Activity1.class);
                    startActivity(appInfo);
                    break;
                case 1 :Intent appInfo = new Intent(About.this, Activity2.class);
                    startActivity(appInfo);
                    break;
                case 2 :Intent appInfo = new Intent(About.this, Activity3.class);
                    startActivity(appInfo);
                    break;

                    BUT DO I NEED REPEAT THIS MORE THAN 20 TIMES?!
                    */

                }
        });
    }
}

像设置这样的一些系统应用有很多 ListView 和布局,我不相信每个布局都有新的活动。

【问题讨论】:

  • 展示你尝试过的东西,请不要指望人们简单地为你写东西。

标签: java android listview android-activity


【解决方案1】:

创建一个新的单个活动并将文本传递给该活动。

类似:

Intent intent = new Intent(About.this, <NEW_ACTIVITY>.class);
intent.putExtra("text_key", items[position]);
startActivity(intent);

在另一个活动上,像这样检索文本(可以在 onCreate 方法上):

String text = getIntent().getExtras().getString("text_key");

【讨论】:

  • 我需要在哪里写我的文字? (对不起中午的问题)
  • 对不起,没关系。起初我不明白,但现在一切都清楚了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多