如何在可扩展列表上实现动态列表视图

时间:2014-02-10 05:46:47

标签: android

我决定将listview作为动态数据,从xml文件中获取详细信息,并显示标题及其图像。

我能够使用带有可扩展列表和listview作为子项的导航抽屉。

继承我的代码:

public class HomeActivity extends Activity {

 // All static variables
static final String URL = "http://test.test.com/vrp/scripts/vrp_data.xml";
// XML node keys
static final String KEY_ELEMENTS = "elements"; // parent node
static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_THUMB_URL = "thumb_url";

ExpandableListAdapter listAdapter;
ExpandableListView expListView;

public DrawerLayout drawer;
ImageView navDrawerBtn;

HashMap<String, List<String>> listDataChild;
List<String> listDataHeader;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    navDrawerBtn = (ImageView)findViewById(R.id.headerDrawer);
    expListView = (ExpandableListView) findViewById(R.id.lvExp);


    if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
        expListView.setIndicatorBounds(402,465);    
    } else {        
        expListView.setIndicatorBoundsRelative(402,465);    
    } 

    drawer = (DrawerLayout)findViewById(R.id.drawer_layout);

    prepareListData();

    navDrawerBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(!drawer.isDrawerOpen(expListView)) {
                drawer.openDrawer(expListView);
                } else {
                    drawer.closeDrawer(expListView);
                }

            }
        });


    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);

    // Listview Group click listener
    expListView.setOnGroupClickListener(new OnGroupClickListener() {

        @Override
        public boolean onGroupClick(ExpandableListView parent, View v,
                int groupPosition, long id) {
            // Toast.makeText(getApplicationContext(),
            // "Group Clicked " + listDataHeader.get(groupPosition),
            // Toast.LENGTH_SHORT).show();
            return false;
        }
    });

    // Listview Group expanded listener
    expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

        @Override
        public void onGroupExpand(int groupPosition) {
            Toast.makeText(getApplicationContext(),
                    listDataHeader.get(groupPosition) + " Expanded",
                    Toast.LENGTH_SHORT).show();
        }
    });

    // Listview Group collasped listener
    expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

        @Override
        public void onGroupCollapse(int groupPosition) {
            Toast.makeText(getApplicationContext(),
                    listDataHeader.get(groupPosition) + " Collapsed",
                    Toast.LENGTH_SHORT).show();

        }
    });

    // Listview on child click listener
    expListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(
                    getApplicationContext(),
                    listDataHeader.get(groupPosition)
                            + " : "
                            + listDataChild.get(
                                    listDataHeader.get(groupPosition)).get(
                                    childPosition), Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
    });
}

/*
 * Preparing the list data
 */
@SuppressWarnings("unchecked")
private void prepareListData() {

    listDataHeader = new ArrayList<String>();
    //listDataChild = new HashMap<String, List<String>>();

    List<HashMap<String, String>> listDataChild = new ArrayList<HashMap<String, String>>();

    com.edataservices.utilities.XMLParser parser = new com.edataservices.utilities.XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML from URL
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ELEMENTS);
    // looping through all song nodes <song>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_ID, parser.getValue(e, KEY_ID));
        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
        map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

        // adding HashList to ArrayList
        listDataChild.add(map);




    // Adding child data
    listDataHeader.add("VRP Medical Bay");
    //listDataHeader.add("");
    //listDataHeader.add("");

    // Adding child data
    List<String> listUnderVRP = new ArrayList<String>();
    listUnderVRP.add("eDataClinical");
    listUnderVRP.add("Schedule");
    listUnderVRP.add("View Messages");
    listUnderVRP.add("Reports for Signature");
    listUnderVRP.add("View Billing");
    listUnderVRP.add("View State");

    List<String> nowShowing = new ArrayList<String>();
    nowShowing.add("The Conjuring");
    nowShowing.add("Despicable Me 2");
    nowShowing.add("Turbo");
    nowShowing.add("Grown Ups 2");
    nowShowing.add("Red 2");
    nowShowing.add("The Wolverine");

    List<String> comingSoon = new ArrayList <String>();
    comingSoon.add("2 Guns");
    comingSoon.add("The Smurfs 2");
    comingSoon.add("The Spectacular Now");
    comingSoon.add("The Canyons");
    comingSoon.add("Europa Report");

    ((HashMap<String, List<String>>) listDataChild).put(listDataHeader.get(0), listDataChild); // HeAndroid Custom ListView with Image and Textader, Child data
    //listDataChild.put(listDataHeader.get(1), nowShowing);
    //listDataChild.put(listDataHeader.get(2), comingSoon);

    }
}
 public int GetPixelFromDips(float pixels) {
        // Get the screen's density scale 
        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale
        return (int) (pixels * scale + 0.5f);
    }

}

以下是可扩展列表适配器的代码:

public class ExpandableListAdapter extends BaseExpandableListAdapter {

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
//private LayoutInflater vi;

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public com.edataservices.utilities.ImageLoader imageLoader; 

public ExpandableListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public ExpandableListAdapter(Context context, List<String> listDataHeader,
        HashMap<String, List<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;
    //vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

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

@Override
public View getChildView(int groupPosition, final int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {

    //final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }

    TextView txtListChild = (TextView) convertView
            .findViewById(R.id.lblListItem);

    ImageView thumbImage = (ImageView) convertView
            .findViewById(R.id.thumbnail);

    HashMap<String, String> values = new HashMap<String, String>();
    values = data.get(groupPosition);

    txtListChild.setText(values.get(HomeActivity.KEY_TITLE));
    imageLoader.DisplayImage(values.get(HomeActivity.KEY_THUMB_URL), thumbImage);

    //txtListChild.setText(values.get(key));
    //thumbImage
    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

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

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

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
        View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    Typeface tf = Typeface.createFromAsset(myClass(_context),
                "fonts/Roboto-Regular.ttf");

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);

    lblListHeader.setTypeface(tf);
    lblListHeader.setText(headerTitle);

    return convertView;
}

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

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}
public AssetManager myClass(Context myContext) {
    AssetManager mngr = myContext.getAssets();
    return mngr;

}

}

0 个答案:

没有答案