2016-03-05 23 views
2

我將發佈我所有的代碼。目前我有一個適配器和數據源的活動,生成一個列表視圖。然後,您選擇配方,並使用單獨的適配器將其發送到其他活動。我想要這個活動打開一個新的頁面和配方的描述。這是一本庫克書。目前它將所有食譜打開在一起,我知道爲什麼,但這是我能在它到期之前讓它工作的唯一方法。有趣的是,我錯過了1分鐘的截止日期,因爲我在string.xml中輸入了所有數據。我嘗試了多種不同的方式來打開一個頁面(配方),但無法讓他們工作。無論如何,這裏是代碼。只從項目清單(食譜)打開選定的項目(食譜)烹飪書籍程序Android Studio

主要活動:

public class RecipesActivity extends AppCompatActivity { 

private RecipesDataSource ds; 
ListView recipes; 
TextView recipesRecipe; 
String[] titles = {"Venison(Deer) Steak", "Hamburger Steak with Onions and Gravy", "Chicken Teriyaki(Pan Fried)", "Chicken and Waffles(Sweet Hot Fried)", "Chicken Alfredo", "Meatloaf", "French Toast Waffles"}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_recipes); 

    ds = new RecipesDataSource(); 

    recipes = (ListView) findViewById(R.id.recipesListView); 
    recipes.setAdapter(new RecipesDataSourceAdapter(this, ds)); 
    //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,titles); 
    //recipes.setAdapter(adapter); 

    recipes.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      Toast.makeText(RecipesActivity.this, "You chose " + titles[position] + ".", Toast.LENGTH_LONG).show(); 
      Intent intent = null; 
      //String selectedFromList =(String)(recipes.getItemAtPosition(position); 
      if(intent == null) { 
       intent = new Intent(getBaseContext(), RecipesDetailActivity.class); 
       startActivity(intent); 
      } 
     } 
    }); 
} 
} 

數據源:

public class RecipesDataSource { 
private ArrayList<Integer> photoPool; 
private ArrayList<Integer> descriptionPool; 
private ArrayList<Integer> dishesPool; 
private ArrayList<Integer> recipesPool; 

public ArrayList<Integer> getPhotoPool() { 
    return photoPool; 
} 

public ArrayList<Integer> getDescriptionPool() { 
    return descriptionPool; 
} 

public ArrayList<Integer> getDishesPool() { 
    return dishesPool; 
} 

public ArrayList<Integer> getRecipesPool() { 
    return recipesPool; 
} 

public RecipesDataSource(){ 
    photoPool = new ArrayList<Integer>(); 
    descriptionPool = new ArrayList<Integer>(); 
    dishesPool = new ArrayList<Integer>(); 
    recipesPool = new ArrayList<Integer>(); 
    setupPhotoPool(); 
    setupDishesPool(); 
    setupDescriptionPool(); 
    setupRecipesPool(); 
} 
public void setupRecipesPool(){ 
    recipesPool.add(R.string.recipeName1); 
    recipesPool.add(R.string.recipeName2); 
    recipesPool.add(R.string.recipeName3); 
    recipesPool.add(R.string.recipeName4); 
    recipesPool.add(R.string.recipeName5); 
    recipesPool.add(R.string.recipeName6); 
    recipesPool.add(R.string.recipeName7); 
} 

public void setupPhotoPool(){ 
    photoPool.add(R.drawable.venisonsteak); 
    photoPool.add(R.drawable.hamburgersteak); 
    photoPool.add(R.drawable.chickenteriyaki); 
    photoPool.add(R.drawable.chickenandwaffles); 
    photoPool.add(R.drawable.chickenalfredo); 
    photoPool.add(R.drawable.meatloaf); 
    photoPool.add(R.drawable.frenchtoastwaffles); 
} 

public void setupDishesPool(){ 
    dishesPool.add(R.string.recipe1); 
    dishesPool.add(R.string.recipe2); 
    dishesPool.add(R.string.recipe3); 
    dishesPool.add(R.string.recipe4); 
    dishesPool.add(R.string.recipe5); 
    dishesPool.add(R.string.recipe6); 
    dishesPool.add(R.string.recipe7); 
} 

public void setupDescriptionPool(){ 
    descriptionPool.add(R.string.description1); 
    descriptionPool.add(R.string.description2); 
    descriptionPool.add(R.string.description3); 
    descriptionPool.add(R.string.description4); 
    descriptionPool.add(R.string.description5); 
    descriptionPool.add(R.string.description6); 
    descriptionPool.add(R.string.description7); 
} 

public int getDataSourceLength(){ 
    return photoPool.size(); 
} 
} 

適配器1:

public class RecipesDataSourceAdapter extends BaseAdapter { 
private Context myContext; 
private LayoutInflater myInflater; 
private RecipesDataSource myDataSource; 

public RecipesDataSourceAdapter(Context ctx,RecipesDataSource ds){ 
    myContext = ctx; 
    myDataSource = ds; 
    myInflater = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public int getCount() { 
    return myDataSource.getDataSourceLength(); 
} 

@Override 
public Object getItem(int position) { 
    return (position); 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView thumbnail; 
    TextView name; 

    if(convertView==null) { 
     convertView = myInflater.inflate(R.layout.list_item_layout, parent, false); 
    } 
    thumbnail = (ImageView)convertView.findViewById(R.id.thumb); 
    thumbnail.setImageResource(myDataSource.getPhotoPool().get(position)); 
    name = (TextView)convertView.findViewById(R.id.text); 
    name.setText(myDataSource.getDishesPool().get(position)); 
    return convertView; 
} 
} 

第二活動:

public class RecipesDetailActivity extends RecipesActivity { 

private RecipesDataSource ds; 
ListView recipesRecipes; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.recipe_page); 

    ds = new RecipesDataSource(); 



    recipesRecipes = (ListView)findViewById(R.id.recipesList); 
    recipesRecipes.setAdapter(new RecipesDetailActivityDataSourceAdapter(this,ds)); 

    } 
} 

第二適配器

public class RecipesDetailActivityDataSourceAdapter extends BaseAdapter { 
private Context myContext; 
private LayoutInflater myInflater; 
private RecipesDataSource myDataSource; 

public RecipesDetailActivityDataSourceAdapter(Context ctx,RecipesDataSource ds){ 
    myContext = ctx; 
    myDataSource = ds; 
    myInflater = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 
@Override 
public int getCount() { 
    return myDataSource.getDataSourceLength(); 
} 

@Override 
public Object getItem(int position) { 
    return (position); 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    TextView recipesRecipe; 
    TextView recipesDescription; 
    if(convertView==null) { 
     convertView = myInflater.inflate(R.layout.recipe_page, parent, false); 
    } 
    recipesRecipe = (TextView)convertView.findViewById(R.id.recipesText); 

    recipesRecipe.setText(myDataSource.getRecipesPool().get(position)); 
    return convertView; 
} 
} 

XML文件: activity_recipes.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<ListView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/recipesListView" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true"/> 

list_item_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 
<ImageView 
    android:id="@+id/thumb" 
    android:layout_width="60dip" 
    android:layout_height="60dip" 
    android:layout_centerVertical="true" 
    android:layout_alignParentLeft="true" 
    /> 
<TextView 
    android:id="@+id/text" 
    android:layout_toRightOf="@+id/thumb" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textSize="18dip" 
    android:layout_marginLeft="10dip" 
    android:layout_centerVertical="true" 
    android:singleLine="true" 
    android:ellipsize="end" 
    android:textStyle="bold" 
    /> 

recipes_page.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<ListView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/recipesList" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true"/> 
<TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/recipesText" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true"/> 

的strings.xml

<resources> 
<string name="app_name">Cook Book</string> 
<string name="recipe1">Venison(Deer) Steak</string> 
<string name="recipe2">Hamburger Steak with Onion and Gravy</string> 
<string name="recipe3">Chicken Teriyaki(pan fried)</string> 
<string name="recipe4">Chicken and Waffles(Sweet Hot Fried)</string> 
<string name="recipe5">Chicken Alfredo</string> 
<string name="recipe6">Meatloaf</string> 
<string name="recipe7">French Toast Waffles</string> 

<string name="description1">Venison(deer) steak is my personal favorite choice of an entree. It is high in nutritional value, superior to beef, pork, and chicken. </string> 
<string name="description2">Easy-to-make classic using hamburger \'steaks\' smothered in gravy and onions.</string> 
<string name="description3">Don\'t have time to fire up that grill? Throw your chicken in a pan and enjoy a delectable chicken teriyaki. Simple and easy to make.</string> 
<string name="description4">Just looking at chicken and waffles gets my mouth watering. Once you make this recipe you won\'t be dissapointed, and will bask in the aroma and sweet yet hot savory flavor of this delectable chicken and waffles combo. </string> 
<string name="description5">A quick and easy chicken alfredo dinner with broccoli, zucchini, and red bell pepper. The sauce is enriched by cream cheese.</string> 
<string name="description6">This is a 211-year-old meatloaf recipe, that has been handed down from generation to generation dating back to 1807. Originally it was made using deer meat, but I prefer using beef as did my Mother. Enjoy.</string> 
<string name="description7">Making French toast in your waffle iron combines the best of both worlds. You get all the custardy richness of French toast plus waffle\'s signature crispy ridges. All the better to hold more maple syrup.</string> 

<string name="recipeName1">\bVenison Steak \nTotal Time 4 hrs 15 mins. \n3 tablespoons canola oil \n1 tablespoon lemon juice \n1 tablespoon worcestershire sauce \n1 tablespoon soy sauce \n1-2 teaspoon minced garlic \n1/2 teaspoon ground pepper \n1 (1 1/2 lb) package venison steak \nDirections: \nMix all marinade ingredients together in a small measuring cup. Place venison steaks in a large zip lock bag.Pour marinade over steaks and seal bag.Place bag in a flat casserole dish so that the steaks are in a single layer.Refrigerate and marinate at least 4 hours, turning every half hour to marinate each side.Drain marinade and grill steaks to desired doneness.I double or triple this recipe for each addition package of steak. Any wild game steak can be used in this recipe. </string> 
<string name="recipeName2">Hamburger Steak with Onions and Gravy \n1 lb ground beef \n1 egg \n1/4 cup bread crumbs \n1/8 teaspoon ground black pepper \n1/2 teaspoon seasoned salt \n1/2 teaspoon onion powder\n1/2 teaspoon garlic powder\n1 teaspoon worcestershire sauce\n1 tablespoon vegetable oil\n1 cup thinly sliced onion\n2 tablespoons all-purpose flour\n1 cup beef broth\n1 tablespoon cooking sherry\nDirections:\n1. In a large bowl, mix together the ground beef, egg, bread crumbs, pepper, salt, onion powder, garlic powder, and Worcestershire sauce. Form into 8 balls, and flatten into patties.\n2. Heat the oil in a large skillet over medium heat. Fry the patties and onion in the oil until patties are nicely browned, about 4 minutes per side. Remove the beef patties to a plate, and keep warm.\n3. Sprinkle flour over the onions and drippings in the skillet. Stir in flour with a fork, scraping bits of beef off of the bottom as you stir. Gradually mix in the beef broth and sherry. Season with seasoned salt. Simmer and stir over medium-low heat for about 5 minutes, until the gravy thickens. Turn heat to low, return patties to the gravy, cover, and simmer for another 15 minutes.</string> 
<string name="recipeName3">Chicken Teriyaki(pan fried) \n340 grams Chicken thighs - boneless skin-on\n 1 teaspoon Ginger - fresh(grated)\n1/4 teaspoon Salt\n2 teaspoons Vegetable oil\n1 tablespoon Honey\n1tablespoon Mirin\n1 tablespoon Sake\n1tablespoon soy sauce\nDirections:\n1. Rub the ginger and and salt into the chicken and let this sit for at least 30 minutes. After it\'s marinated, use paper towels to dry the chicken as best you can, removing any excess ginger pulp.\n2. Heat the oil in a heavy bottomed frying pan over medium heat. You don\'t want to start the chicken off over too high a heat otherwise it will not cook through before burning. Place the chicken skin-side down in the pan and fry until golden brown on one side.\n3. Flip the chicken, then add 1 tablespoon of sake and quickly cover the pan with a lid. Steam the chicken until it is just cooked through (about 5 minutes).\n4. Prepare the teriyaki sauce by mixing 1 tablespoon each of: honey,mirin,sake,and soy sauce. Stir to combine. Remove the lid, and drain any remaining liquid and oil. Use a paper towel to sop up any excess oil.\n5. Turn up the heat to high, then add teriyaki sauce. Let this mixture boil, while flipping the chicken repeatedly to coat evenly.\n6. The chicken teriyaki is done when most of the liquid has evaporated and the sauce forms a thick glaze around the chicken. Slice and pour the remaining teriyaki sauce over the chicken.</string> 
<string name="recipeName4">Chicken and Waffles(Sweet Hot Fried) \nSweet Hot Maple Glaze:\n1 cup honey\n1 cup maple syrup\n1 teaspoon chili powder\n1 teaspoon garlic powder\n1 teaspoon onion powder\n1 teaspoon paprika\n1 teaspoon ground black pepper\n1/2 teaspoon cayenne\n1/2 teaspoon salt\nWaffles:\n2 cupsa all-purpose flour\n2 tablespoons sugar\n2 teaspoons baking powder\n2 teaspoons kosher salt\n2 eggs\n2 cups whole milk\n8 tablespoons (1 stick) unsalted butter, melted\n1 cup shredded sharp cheddar\n1/4 cup chopped fresh scallions\n7 to 8 dashes hot sauce\nFried Chicken:\nOil, for frying\n8 boneless, skin-on chicken thighs\n1 cup buttermilk\2 cups flour\n1 teaspoon garlic powder\n1 teaspoon onion powder\n1 teaspoon paprika\n1 teaspoon ground black pepper\n1 teaspoon salt\nDirections:\nSpecial equipment: a Belgian waffle ironFor the glaze: Heat the honey and maple syrup in a small saucepot until just starting to simmer. Remove from the heat and whisk in the chili powder, garlic powder, onion powder, paprika, black pepper, cayenne and salt. Steep for 20 minutes, then strain into a clean container.For the waffles: Preheat the oven to 250 degrees F and place a rack in the middle of the oven. Place a baking sheet fitted with a wire rack in the oven.Whisk together the flour, sugar, baking powder and salt in a large bowl and set aside.In another large bowl, whisk the eggs until just broken up, then add the milk and, while whisking constantly, slowly pour in the melted butter until combined. Add the cheese, scallions and hot sauce, and stir until combined.Add the wet ingredients to the dry ingredients and stir with a rubber spatula until the flour is just incorporated and no streaks remain (the batter may have a few lumps).Preheat a Belgian waffle iron to medium heat according to the manufacturer\'s instructions. Add some batter, close the lid, and cook until the steam starts to diminish (open the top and peek for doneness after a few minutes). Transfer the waffle to the wire rack in the oven to keep warm. Repeat with the remaining batter to make 8 waffles.For the chicken: Pour 5-inches of oil in a heavy-bottomed pot. Heat over medium-high heat until a deep-frying thermometer inserted in the oil reaches 360 degrees F.Place the chicken thighs and buttermilk in a bowl. In a separate bowl, add the flour, garlic powder, onion powder, paprika, pepper and salt, and mix to combine. Dredge each thigh in the flour mix, then shake off any excess flour and carefully place in the oil. Fry until golden, 7 to 8 minutes. Remove the chicken to a paper bag or paper towels to drain excess grease.Place each piece of fried chicken on top of a waffle and drizzle each with some glaze to serve.Recipe courtesy of Amanda Freitag</string> 
<string name="recipeName5">Chicken Alfredo \n6 ounces dry fettuccine pasta\n1(8 ounce) package cream cheese\n6 tablespoons butter\n1/2 cup milk\n1/2 teaspoon garlic powder\nsalt and pepper to taste\n2 skinless,boneless chicken breast halves - cooked and cubed\n2 cups chopped fresh broccoli\n2 small zucchini, julienned\n1/2cup chopped red bell pepper\nDirections:\n1. Bring a large pot of lightly salted water to a boil. Add pasta, and cook for 8 to 10 minutes, or until al dente; drain.\n2. While pasta is cooking, melt cream cheese and butter in a skillet over low heat. Stir until smooth. Stir in milk, and season with garlic powder, salt, and pepper. Simmer for 3 minutes, or until thickened, stirring constantly.\n3. Mix in chicken, broccoli, zucchini, and red pepper. Cook 3 minutes over medium heat, then reduce heat, and simmer 5 minutes, or until vegetables are tender. Serve over fettuccine. </string> 
<string name="recipeName6">Meatloaf \n2 pounds ground beef\n2 tablespoons water\n1 tablespoon milk\n1 cup bread crumbs\n1 onion, diced\n1 small Granny Smith apple,diced\n1 egg\nDirections:\n1. Preheat the oven to 375 degrees F(190 degrees C)\n2. Mix ground beef with water and milk in a large bowl using your hands until beef is evenly moistened.\n3. Mix bread crumbs, onion, carrot, apple, and egg into the beef mixture until evenly integrated.\n4. Form the beef mixture into a loaf.\n5. Transfer the meatloaf to a deep baking dish; tent with a sheet of aluminum foil.\n6. Bake in preheated oven for 1 hour; remove foil tent and bake until no longer pink the center, about 30 minutes more.</string> 
<string name="recipeName7">French Toast Waffles \ncooking spray\n1/2 cup whole milk\n2 large eggs\n1 tablespoon maple syrup\n1/2 teaspoon vanilla extract\n1 pinch salt\n4 pieces 1/2-inch thick pieces brioche\nDirections:\n1. Preheat a waffle iron according to manufacturer\'s instructions and spray with cooking spray.\n2. Whisk milk, eggs, maple syrup, vanilla extract, and salt together in a wide bowl until thoroughly combined. Dip bread slices 1 at a time in the egg mixture, coating both sides completely. Lift bread with a slotted spatula to allow excess egg mixture to drain back into the bowl. Place dipped bread slices on a rimmed baking sheet and let rest until mixture soaks in, about 2 minutes.\n3. Place dipped bread in the preheated waffle iron. Gently close the lid without forcing it down. Cook according to manufacturer\'s instructions until golden brown, 3 to 5 minutes. Repeat with remaining slices. </string> 

AndroidManifest.xml中

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="cj.cookbook"> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".RecipesActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity android:name=".RecipesDetailActivity"> 
    </activity> 
</application> 

+1

呃,爲了我所看到的,您將整個數組傳遞給第二個適配器,您不能指望其他任何東西......嘗試在第二個適配器的getCount上返回1,您將明白我的意思。 – RominaV

+1

我假設會打印第一個recipe.I'm認爲我必須編輯onItemClick在第一個活動比較所選的位置?或者我可以在第二個適配器下的getCount?或者在第二個適配器中查看我假設我將不得不改變這一行recipesRecipe.setText(myDataSource.getRecipesPool()。get(position)); – ChrisFocker

回答

2

我改變了第二個活動(改變ListView控件到的TextView)

public class RecipesDetailActivity extends RecipesActivity 
{ 
private RecipesDataSource ds; 
TextView recipesRecipes; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.recipe_page); 
    Intent intent = getIntent(); 
    ds = new RecipesDataSource(); 
    int position = intent.getIntExtra("POSITION", 0); 
    recipesRecipes = (TextView)findViewById(R.id.recipesText); 
    recipesRecipes.setText(ds.getRecipesPool().get(position)); 
} 
} 

,改變了第一次活動是在項目點擊收聽到

recipes.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      Toast.makeText(RecipesActivity.this, "You chose " + titles[position] + ".", Toast.LENGTH_LONG).show(); 
      Intent intent = null; 
      //String selectedFromList =(String)(recipes.getItemAtPosition(position); 
      intent = new Intent(getBaseContext(), RecipesDetailActivity.class); 
      intent.putExtra("POSITION",position); 
      startActivity(intent); 
      } 
    }); 

在recipe_page.xml 拿出的ListView這使得第二個適配器不必要,所以我刪除了它。

1

當調用的第二個活動,你應該通過單擊的位置。 在您的第一項活動:

@Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     Toast.makeText(RecipesActivity.this, "You chose " + titles[position] + ".", Toast.LENGTH_LONG).show(); 
     Intent intent = null; 
     //String selectedFromList =(String)(recipes.getItemAtPosition(position); 
     if(intent == null) { 
      intent = new Intent(getBaseContext(), RecipesDetailActivity.class); 
      intent.putExtra("POSITION", position); 
      startActivity(intent); 
     } 
    } 

現在你應該得到它的第二個活動:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.recipe_page); 
    Intent intent = getIntent(); 
    int position = intent.getIntExtra("position"); 
} 

有你有你的位置。在那之後,它對你想要做的事情感到困惑;例如,第二個適配器不會編譯,在getItem中返回(位置)?目前尚不清楚您訪問的是哪個陣列。

+0

這一切都可以在一個適配器中完成嗎? – ChrisFocker

+0

@ChrisFocker我真的沒有看到這樣做的優勢;但如果你想這樣做,你應該只列出一個你想要顯示的元素,如列表 oneItemList = new ArrayList <>(); ,然後oneItemList.add(yourFullList.get(position)); (其中位置是在意圖中獲得的位置)。 – RominaV

+0

@ChrisFocker此外,我建議不要使用單個項目的適配器;相反,我會誇大單個項目的單一視圖。 – RominaV