1

这是一个漂亮的千篇一律的程序,它扩展了一个列表,然后当你点击一个孩子时,它会弹出一条消息,说“孩子点击了”。但我希望可扩展列表包含食谱,以便在单击时显示一个弹出窗口的成分。我尝试将其设置为对象数组列表而不是字符串,并让对象包含成分列表,但是在尝试显示成分时我感到很困惑..提前致谢!

package com.poe.poeguide;

import java.util.ArrayList;
import com.actionbarsherlock.app.SherlockActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.MenuItem;
import android.widget.ExpandableListView.OnChildClickListener;

public class Recipes extends SherlockActivity {
private ExpandableListView mExpandableList;

 /** An array of strings to populate dropdown list */
String[] actions = new String[] {
   "Recipes",
   "Main Page",
   "Attributes",
};

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

    /** Create an array adapter to populate dropdownlist */
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.sherlock_spinner_item, actions);

    /** Enabling dropdown list navigation for the action bar */
    getSupportActionBar().setNavigationMode(com.actionbarsherlock.app.ActionBar.NAVIGATION_MODE_LIST);

    /** Defining Navigation listener */
    ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {


        @Override
        public boolean onNavigationItemSelected(int itemPosition, long itemId) {
            switch(itemPosition) {
            case 0:

                break;
            case 1:
                Intent a = new Intent(Recipes.this, MainActivity.class);
                startActivity(a);
                break;
            }
            return false;
        }

    };

    getSupportActionBar().setListNavigationCallbacks(adapter, navigationListener);
    adapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);



    mExpandableList = (ExpandableListView)findViewById(R.id.expandable_list);

    ArrayList<Parent> arrayParents = new ArrayList<Parent>();
    ArrayList<String> arrayChildren = new ArrayList<String>();

    //======================================================================================
    //here we set the parents and the children
        //for each "i" create a new Parent object to set the title and the children
        Parent parent = new Parent();
        parent.setTitle("Pies");
        arrayChildren.add("Apple Pie ");
        arrayChildren.add("Blueberry Pie ");
        parent.setArrayChildren(arrayChildren);

        //in this array we add the Parent object. We will use the arrayParents at the setAdapter
        arrayParents.add(parent);

    //======================================================================================

    //sets the adapter that provides data to the list.
    mExpandableList.setAdapter(new MyCustomAdapter(Recipes.this,arrayParents));

    mExpandableList.setOnChildClickListener(new OnChildClickListener()
    {

        @Override
        public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2, int arg3, long arg4)
        {
            Toast.makeText(getBaseContext(), "Child clicked", Toast.LENGTH_LONG).show();
            return false;
        }
    });

}


@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    getSupportMenuInflater().inflate(R.menu.activity_recipes, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

4

1 回答 1

2

在我们开始之前,请注意这Recipes是一个令人困惑的 Activity 名称。我强烈建议更改名称以遵循以“活动”一词结尾的标准约定(例如,RecipeActivity)。


首先,您需要创建一个Recipe对象,以便将名称和成分存储在一起。这个对象可以根据需要简单或复杂,但让我们假设它看起来像这样:

import java.util.List;

public class Recipe {
    private String name;
    private List<String> ingredients;
    private List<String> directions;

    @Override
    public String toString() {
        // By default, the Adapter classes in Android will call toString() on
        // your object to figure out how it should appear in lists. To make sure
        // the list displays the recipe name, we return the recipe name here.
        return name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getIngredients() {
        return ingredients;
    }

    public void setIngredients(List<String> ingredients) {
        this.ingredients = ingredients;
    }

    public List<String> getDirections() {
        return directions;
    }

    public void setDirections(List<String> directions) {
        this.directions = directions;
    }
}

请注意,我们覆盖toString()此对象并返回配方名称。这样,当我们要求适配器类显示Recipe对象列表时,它就知道应该为列表中的每个项目显示什么文本。


在为您的列表创建数据时,而不是:

ArrayList<String> arrayChildren = new ArrayList<String>();

利用:

List<Recipe> arrayChildren = new ArrayList<Recipe>();

(注意:如果该字段现在只接受,您可能需要修改Parent要采用的类List<Recipe>或子类的泛型。)List<?>List<String>

让我们添加一个示例Recipe对象:

Recipe salsa = new Recipe();
salsa.setName("Pineapple Salsa");
salsa.setIngredients(Arrays.asList("pineapple", "cilantro", "lime", "jalapeno"));
salsa.setDirections(Arrays.asList("Blend ingredients and enjoy"));
arrayChildren.add(salsa);

现在您的列表由Recipe对象支持,而不仅仅是字符串,只需在单击列表项时获取该对象即可。您可以这样做:

mExpandableList.setOnChildClickListener(new OnChildClickListener() {
    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
            int groupPosition, int childPosition, long id) {
        // Get the selected recipe
        Recipe recipe = (Recipe) parent.getExpandableListAdapter()
                .getChild(groupPosition, childPosition);

        // Build a string listing the ingredients
        StringBuilder message = new StringBuilder("Ingredients:\n");
        for (String ingredient : recipe.getIngredients())
            message.append("\n").append(ingredient);

        // Display a dialog listing the ingredients
        new AlertDialog.Builder(MyGreatHelloWorldActivity.this)
                .setTitle(recipe.getName()).setMessage(message)
                .setPositiveButton("Yum!", null).show();

        // Return true because we handled the click
        return true;
    }
});

更新:以下是使用可扩展列表的简洁适配器完成任务的方法。

我创建了一个名为ExpandableListGroup (相当于你的Parent类)的通用类来容纳孩子。该类是通用的,因此它可以与任何类型的对象一起使用,但我们会将它与Recipe对象一起使用。

import java.util.List;

public class ExpandableListGroup<T> {
    private String name;
    private List<T> children;

    public ExpandableListGroup(String name, List<T> children) {
        this.name = name;
        this.children = children;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<T> getChildren() {
        return children;
    }

    public void setChildren(List<T> children) {
        this.children = children;
    }

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

然后我创建了以下泛型ExpandableListArrayAdapter类:

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class ExpandableListArrayAdapter<T> extends BaseExpandableListAdapter {
    private List<ExpandableListGroup<T>> groups;
    private LayoutInflater inflater;

    public ExpandableListArrayAdapter(Context context,
            List<ExpandableListGroup<T>> groups) {
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.groups = groups;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        ExpandableListGroup<T> group = getGroup(groupPosition);
        if (convertView == null) {
            convertView = inflater.inflate(
                    android.R.layout.simple_expandable_list_item_1, parent,
                    false);
        }

        TextView text = (TextView) convertView;
        text.setText(group.toString());
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        T item = getChild(groupPosition, childPosition);
        if (convertView == null) {
            convertView = inflater.inflate(
                    android.R.layout.simple_expandable_list_item_1, parent,
                    false);
        }

        TextView text = (TextView) convertView;
        text.setText(item.toString());
        return convertView;
    }

    @Override
    public T getChild(int groupPosition, int childPosition) {
        return groups.get(groupPosition).getChildren().get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return groups.get(groupPosition).getChildren().size();
    }

    @Override
    public ExpandableListGroup<T> getGroup(int groupPosition) {
        return groups.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return groups.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

现在,这是你如何将它们联系在一起的方法:

// Create one list per group
List<Recipe> appetizers = new ArrayList<Recipe>(),
        desserts = new ArrayList<Recipe>();

// TODO: Create Recipe objects and add to lists

List<ExpandableListGroup<Recipe>> groups = Arrays.asList(
        new ExpandableListGroup<Recipe>("Appetizers", appetizers),
        new ExpandableListGroup<Recipe>("Desserts", desserts));
mExpandableList.setAdapter(new ExpandableListArrayAdapter<Recipe>(this,
        groups));
于 2012-12-23T05:35:22.687 回答