Android 在可展开列表中选择子项时如何合并弹出窗口

Android 在可展开列表中选择子项时如何合并弹出窗口,android,drop-down-menu,actionbarsherlock,expandablelistview,popupwindow,Android,Drop Down Menu,Actionbarsherlock,Expandablelistview,Popupwindow,这里有一个漂亮的cookiecuter程序,它可以扩展一个列表,然后当你点击一个孩子时,它会弹出一条消息说,“孩子点击了”。但是我希望这个可扩展的列表由食谱组成,这样当点击时,它会显示一个成分的弹出窗口。我试着让它成为一个对象的arraylist,而不是字符串,并且让对象包含成分列表,但是当我试图显示成分时,我把一切都搞得一团糟。。提前谢谢 package com.poe.poeguide; import java.util.ArrayList; import com.actionbarshe

这里有一个漂亮的cookiecuter程序,它可以扩展一个列表,然后当你点击一个孩子时,它会弹出一条消息说,“孩子点击了”。但是我希望这个可扩展的列表由食谱组成,这样当点击时,它会显示一个成分的弹出窗口。我试着让它成为一个对象的arraylist,而不是字符串,并且让对象包含成分列表,但是当我试图显示成分时,我把一切都搞得一团糟。。提前谢谢

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);
}
包com.poe.poeguide;
导入java.util.ArrayList;
导入com.actionbarsherlock.app.SherlockActivity;
导入android.content.Intent;
导入android.os.Bundle;
导入android.support.v4.app.NavUtils;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.ExpandableListView;
导入android.widget.Toast;
导入com.actionbarsherlock.app.ActionBar;
导入com.actionbarsherlock.app.ActionBar.OnNavigationListener;
导入com.actionbarsherlock.view.MenuItem;
导入android.widget.ExpandableListView.OnChildClickListener;
公共类食谱扩展了Sherlock活动{
私有可扩展列表视图mExpandableList;
/**用于填充下拉列表的字符串数组*/
字符串[]操作=新字符串[]{
“食谱”,
“主页”,
“属性”,
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipes);
/**创建阵列适配器以填充dropdownlist*/
ArrayAdapter=新的ArrayAdapter(getBaseContext(),R.layout.sherlock\u微调器\u项,操作);
/**为操作栏启用下拉列表导航*/
getSupportActionBar().setNavigationMode(com.actionbarsherlock.app.ActionBar.NAVIGATION\u MODE\u列表);
/**定义导航侦听器*/
ActionBar.OnNavigationListener navigationListener=新建OnNavigationListener(){
@凌驾
公共布尔值onNavigationItemSelected(int-itemPosition,long-itemId){
开关(位置){
案例0:
打破
案例1:
意图a=新意图(Recipes.this,MainActivity.class);
星触觉(a);
打破
}
返回false;
}
};
getSupportActionBar().setListNavigationCallbacks(适配器、navigationListener);
adapter.setDropDownViewResource(R.layout.sherlock\u微调器\u下拉菜单\u项);
mExpandableList=(ExpandableListView)findViewById(R.id.ExpandableList);
ArrayList arrayParents=新的ArrayList();
ArrayList arrayChildren=新的ArrayList();
//======================================================================================
//我们把父母和孩子放在这里
//为每个“i”创建一个新的父对象以设置标题和子对象
父项=新父项();
母公司。设定所有权(“Pies”);
arrayChildren.add(“苹果派”);
arrayChildren.添加(“蓝莓派”);
parent.setArrayChildren(arrayChildren);
//在此数组中,我们添加父对象。我们将在setAdapter中使用arrayParents
arrayParents.add(父级);
//======================================================================================
//设置向列表提供数据的适配器。
setAdapter(新的MyCustomAdapter(Recipes.this,arrayParents));
setOnChildClickListener(新的OnChildClickListener())
{
@凌驾
公共布尔onChildClick(ExpandableListView arg0、视图arg1、int arg2、int arg3、long arg4)
{
Toast.makeText(getBaseContext(),“Child clicked”,Toast.LENGTH_LONG.show();
返回false;
}
});
}
@凌驾
公共布尔onCreateOptions菜单(com.actionbarsherlock.view.Menu菜单){
getSupportMenuInflater().充气(R.menu.activity\u菜谱,菜单);
返回super.onCreateOptions菜单(菜单);
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例android.R.id.home:
//此ID表示“主页”或“向上”按钮
//活动中,将显示向上按钮。使用NavUtils允许用户
//在应用程序结构中向上导航一级。对于
//更多详细信息,请参见Android Design上的导航模式:
//
// http://developer.android.com/design/patterns/navigation.html#up-对背
//
NavUtils.navigateUpFromSameTask(本);
返回true;
}
返回super.onOptionsItemSelected(项目);
}

}

在开始之前,请注意,
菜谱
是一个令人困惑的活动名称。我强烈建议更改名称,以遵循以“活动”一词结尾的标准惯例(例如,
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;
    }
}
使用:

既然列表由
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
(相当于您的
父类
类)的通用类来容纳子类。该类是泛型的,因此它可以处理任何类型的对象,但我们将它用于
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;
    }
}
现在,以下是如何将所有这些联系在一起:

// 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));
//为每个组创建一个列表
列出开胃菜=新ArrayList(),
甜点=新的ArrayList();
//TODO:创建配方对象并添加到列表
列表组=Arrays.asList(
新的可扩展列表组(“开胃菜”,开胃菜),
新可扩展
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;
    }
});
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;
    }
}
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));