【问题标题】:Launch an Activity from Android ListView and populate based on selection从 Android ListView 启动一个 Activity 并根据选择进行填充
【发布时间】:2012-07-16 18:52:03
【问题描述】:

我目前有一个 Android ListView 类,它显示大约 20 个主题(字符串)的列表。我需要能够单击列表中的每个按钮并让该按钮打开特定于该主题的视图。

例如,如果这是一个菜谱列表,那么所有菜谱视图的布局可能相同,但是当用户从列表中单击特定菜谱时,程序必须将该菜谱加载到通用布局中并将用户带到该视图。

我认为 OnItemClickListener 可以正常工作,但我不确定如何实现其余部分。

每个食谱都需要新的活动和布局吗?有没有更简单的方法来实现这一点,而无需制作数十个相同的布局和活动文件?

另外,我将如何使用配方填充视图?

非常感谢您提供任何有用的想法!

--- 一些相关代码:Listview 活动代码

listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, studiesList);  

    // Set the ArrayAdapter as the ListView's adapter.  
    mainListView.setAdapter( listAdapter );    
    mainListView.setClickable(true);
    mainListView.setOnItemClickListener(new OnItemClickListener(){

        public void onItemClick(AdapterView<?> a, View view, int position, long id) { 

            switch( position )
            {
               case 0:  Intent intent = new Intent(StudyActivity.this, pos.class); 
                        startActivity(intent);
                        break;

SimpleRow.xml 文件:(列表的按钮)

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</Button>

【问题讨论】:

    标签: android listview android-activity click


    【解决方案1】:

    您需要做的是创建一个具有一些属性的可序列化配方类,然后为 20 个配方中的每一个创建该类的新对象。

    我假设你会有类似的东西

    public class Recipe extends Serializable{ 
    private String name; 
    private String ingredients; 
    
    public Recipe(String name, String ingredients){
    this.name = name;
    this.ingredients = ingredients;
    }
    

    }

    然后制作这些对象的数组列表

    ArrayList<Recipe> recipes = new ArrayList<Recipe>();
    recipes.add(new Recipe("Chicken Curry", "Random cooking instructions"));
    

    并在您的列表适配器中使用该数组列表。

    然后在你的 onItemClickListener 中你需要类似的东西

    Intent i = new Intent(this, recipeDisplay.class)
    i.putExtra("recipe",  listAdapter.getItemAtPosition(position)); 
    

    在您的食谱显示类中,只需接收意图并使用该对象来填充您的活动字段。

    Intent intent = getIntent():
    intent.getSerializableExtra("recipe");
    

    【讨论】:

    • 太棒了!非常感谢您的快速回复!我会试试的!
    【解决方案2】:

    我想你会想要在一个新的 Activity 中打开食谱,它可以有一个标准的“食谱”视图。

    要将数据传递给新 Activity,您可以向将启动新 Activity 的 Intent 添加额外内容(请参阅 API 文档中的 Intents and Intent Filters- Extras)。您可以传递一个 int 或一个 String 来标识您想要的配方。

    在 Intent 中传递 extras 的基本大纲是:

    Intent intent = new Intent(this, NextActivity.class);
    intent.putExtra("EXTRA_ID", data);
    startActivity(intent);
    

    然后,在新的 Activity 中你可以获得这些值:

    Bundle extras = getIntent().getExtras();
    if(extras.hasExtra("EXTRA_ID")) {
        int value = extras.getString("EXTRA_ID");
    }
    

    使用该值从您获取数据的任何来源加载配方,您应该一切就绪!

    【讨论】:

    • 太棒了!非常感谢您的快速回复!我会试试的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多