ExpandableListActivity获取文本

时间:2012-06-13 14:41:28

标签: android

我在每个项目中ExpandableListActivity都有Text。 如何获取点击列表项目的文本?

以下是我的表现:

        groupData = application.getFirstLayer();
        String groupFrom[] = new String[] {"groupName"};
        int groupTo[] = new int[] {android.R.id.text1};

        childData = application.getSecondLayer();
        String childFrom[] = new String[] {"levelTwoCat"};
        int childTo[] = new int[] {android.R.id.text1};

        adapter = new SimpleExpandableListAdapter(
            this,
            groupData,
            android.R.layout.simple_expandable_list_item_1,
            groupFrom,
            groupTo,
            childData,
            android.R.layout.simple_list_item_1,
            childFrom,
            childTo);


public boolean onChildClick(android.widget.ExpandableListView parent,
            View v, int groupPosition, int childPosition, long id) {}

为了查看当前项目的文本,我必须在onChildClick中写一下?

1 个答案:

答案 0 :(得分:1)

最简单的方法是直接从您单击的视图中获取它。您没有显示行XML,因此以下代码将假设您有一个LinearLayout,其中包含TextView作为您的行。

public boolean onChildClick(android.widget.ExpandableListView parent, 
        View v, int groupPosition, int childPosition, long id) {

            TextView exptv = (TextView)v.findViewById(R.id.yourtextview); //  Get the textview holding the text
            String yourText = exptv.getText().toString();  // Get the text from the view and put it in a string
            // use string as you need to
}

如果布局是一个文本视图,您可以直接转到String yourText = v.getText().toString();,因为传入的View v将是您需要的TextView。

修改

正如Jason Robinson在评论中指出的那样,你使用android.R.layout.simple_list_item_1作为你的子布局,因为那只是一个TextView,它简化了你需要的代码:

public boolean onChildClick(android.widget.ExpandableListView parent, 
        View v, int groupPosition, int childPosition, long id) {

            String yourText = v.getText().toString();  // Get the text from the view and put it in a string
            // use string as you need to
}