从Android ListView启动一个Activity并根据选择进行填充

时间:2012-07-16 18:52:03

标签: android listview android-activity click

我目前有一个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>

2 个答案:

答案 0 :(得分:0)

我认为您想要做的是在新的活动中打开配方,该活动可以有一个标准的“配方”视图。

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

在Intent中传递额外内容的基本概要是:

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");
}

使用该值从您从中获取数据的任何来源加载配方,您应该全部设置!

答案 1 :(得分:0)

您需要做的是创建一个带有某些属性的可序列化配方类,然后为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"));

并在列表适配器中使用该arraylist。

然后在你的onItemClickListener中你需要像

这样的东西
Intent i = new Intent(this, recipeDisplay.class)
i.putExtra("recipe",  listAdapter.getItemAtPosition(position)); 

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

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