从列表适配器调用片段

时间:2013-02-09 02:34:21

标签: android android-fragments android-listfragment android-sliding

我在我的应用中使用滑动菜单/抽屉图案。所以main活动有一个leftView,它是一个名为topicsFragment()的ListFragment,它加载了一组主题项。单击某个项目/主题时,它将通过调用FeedsFragment(标记)替换主视图上的片段。 FeedsFragment使用arraylist适配器加载在每个列表项中具有各种可点击项的源。我想在列表项中单击项目时在feedsFragment(标记)上获取另一个实例。

    holder.contextView= (TextView) newsView.findViewById(R.id.arcHeader);
    if (item.hasArc()) {
        holder.contextView.setVisibility(View.VISIBLE);
        String arc;
        try {
            arc=item.getarc();
            holder.contextView.setText(arc);

            holder.contextView.setOnClickListener(new View.OnClickListener() {

                //currently it loads a class
                @Override
                public void onClick(View v) { 
                   Intent i = new Intent(context, SomeClass.class); 
                   i.putExtra("tag", arc);
                   context.startActivity(i);
                }
            });
        } catch (JSONException e) {

            e.printStackTrace();
        }

    } else {
        holder.contextView.setVisibility(View.GONE);
    }

目前它加载了一个新类。我想定义一个片段,然后传递给main活动以替换当前视图,但我不能在适配器类中使用getSupportFragmentManager(),而只能在片段或片段活动中使用。什么应该是从适配器扫描片段的替代方法?

4 个答案:

答案 0 :(得分:3)

我所做的是在我的主要活动中创建此方法,并从其他类中调用它来更改片段:

public void switchContent(Fragment fragment) {
        mContent = fragment;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();

        slidemenu.showContent();

    }

答案 1 :(得分:3)

使用列表适配器中传递的上下文解决它:

@Override
public void onClick(View v) {
    Fragment newFragment = new ListFragmentClass(tag);
    if (newFragment != null)
        switchFragment(newFragment);
}

private void switchFragment(Fragment newFragment) {
    if (context == null)
        return;
    if (context instanceof MainActivity) {
        MainActivity feeds = (MainActivity) context;
        feeds.switchContent(newFragment);
    }
}

这里switchContent是在主要活动中定义的方法,用于切换/替换片段,如Justin V的答案所示。

答案 2 :(得分:0)

getFragmentManager()作为参数传递给适配器的构造函数并使用它。

答案 3 :(得分:0)

使用Interface将您的侧抽屉ListFragment连接到主要活动。例如:

public class LeftDrawer extends ListFragment{

    private DrawerCallback mCallback;

    public interface DrawerCallback{
        public void onListClick(String tag);
    }

    public void setCallback(DrawerCallback callback){
        mCallback = callback;
    }

} 

由于Fragments应该有一个空构造函数,请在Fragment中使用公共方法设置回调,然后再将FragmentTransaction添加到抽屉中。此时剩下的就是通知您的Fragment发生了点击。您应该做的是直接捕获ListFragment中的单击,而不是将onClickListener添加到适配器中的每个视图。

 @Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    /*
     * Get item at the clicked position from your adapter and
     * get its string tag before triggering interface
     */
   mCallback.onListClick(tag);
}

使用onListItemClick方法执行此操作。您将获得单击的列表位置,然后可以轻松地从适配器获取该项目并获取其标记值以传递回主机活动。

相关问题