如何从ListAdapter更改片段的Lis​​tView中的数据?

时间:2013-09-18 00:33:15

标签: java android listview android-listview android-fragments

我有一个包含一些ListView的片段。我有我的ListAdapter,它自定义ListViews,这样只有一个组会显示一个按钮并向该按钮添加一个OnClickListener。我试图让OnClickListener将一个项目添加到我的片段中的一个列表中,但问题是我无法找到如何与我的片段中的任何方法进行交互。也许,除了直接通过ListAdapter之外,还有一种更好的方法。

SlidingMenuFragment.java - 片段

/**
 * Adds a child to favorite locations section list
 * @param v the view
 * @param location the location to add
 */
public void addFavoriteLocation(View v, String location){
    mFavoriteLocationsSection.addSectionItem(99, "test location", "slidingmenu_clear");//TODO change dummy values
    sectionListAdapter.notifyDataSetChanged();
}

SectionListAdapter.java - 列表适配器

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
        View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.slidingmenu_sectionview,
                parent, false);
    }

    TextView textView = (TextView) convertView
            .findViewById(R.id.slidingmenu_section_title);
    textView.setText(((Section) getGroup(groupPosition)).getTitle());

    //Sets the group "Favorite Locations" to have the only add_button as VISIBLE, and other groups to GONE
    //Set an onClickListener to add button as well
    if( sections.get(groupPosition).getTitle().equalsIgnoreCase("Favorite Locations") ){
        convertView.findViewById(R.id.favoritelocations_addbutton).setVisibility(View.VISIBLE);//works
        convertView.findViewById(R.id.favoritelocations_addbutton).setOnClickListener(new OnClickListener() {//doesnt

            @Override
            public void onClick(View v) {
                //I am trying to call addFavoriteLocation(...) here, but can't figure out how to do so
            }
        });
        }else{
            convertView.findViewById(R.id.favoritelocations_addbutton).setVisibility(View.GONE);
        }

    return convertView;
}

1 个答案:

答案 0 :(得分:0)

我终于弄明白了......在我的OnClickListener

MainActivity mainAct = (MainActivity) context;
mainAct.addFavoriteLocation