4

我是 Android 编程的新手,正在尝试弄清楚如何去做。我有一个托管内部选项卡的片段,其中一个是 ListFragment。在 tabhost 片段上,我有一个调用 DialogFragment 的按钮。当在该 DialogFragment 上单击“是”时,如果 ListFragment 当前处于活动状态,我需要刷新它以显示添加到列表中的项目。

解决此问题的最佳方法是什么?我在想我应该在 DialogFragment 上放置一个接口,然后在 Activity 上实现侦听器,然后在 ListFragment 中调用刷新。我需要能够拉出 ListFragment 的标签以确定它是否处于活动状态,但是不知道该怎么做。

几个月前我刚开始学习编程,这是我在这个网站上的第一篇文章。我搜索了这个答案,找不到任何东西。如果我的方法或格式有误,我深表歉意。任何提示表示赞赏,谢谢。

标签片段:

public class Items extends Fragment implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, View.OnClickListener {
    MyPageAdapter pageAdapter;
    private ViewPager mViewPager;
    private TabHost mTabHost;

    static final String ARG_ID = "id";
    static final String name = "name";
    long id;
    String itemName;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.tab_test);
        Bundle args = getArguments();
        long id = args.getLong(ARG_ID);
        String itemName = args.getString(name);

        View v = inflater.inflate(R.layout.item_tab, container, false);
        mViewPager = (ViewPager) v.findViewById(R.id.pager);

        // Tab Initialization
        //initialiseTabHost
        mTabHost = (TabHost) v.findViewById(android.R.id.tabhost);
        mTabHost.setup();

        // TODO Put here your Tabs
        List<Fragment> fragments = getFragments();
        FragmentActivity context = getActivity();

        this.AddTab(context, this.mTabHost, this.mTabHost.newTabSpec("ItemList").setIndicator("ItemList"));

        mTabHost.setOnTabChangedListener(this);


        // Fragments and ViewPager Initialization

        pageAdapter = new MyPageAdapter(getChildFragmentManager(), fragments);
        mViewPager.setAdapter(pageAdapter);
        mViewPager.setOnPageChangeListener(this);

        if (savedInstanceState == null) {

        }else {
            int pos = savedInstanceState.getInt("tab");
            mTabHost.setCurrentTab(pos);
        }

        Button addItemButton = (Button) v.findViewById(R.id.addItem);
        addItemButton.setOnClickListener(this);

        return v;
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addItem:
                DialogFragment addItem = new AddItemDialogFragment();
                Bundle itemArgs = getArguments();
                addItem.setArguments(itemArgs);
                addItem.show(getChildFragmentManager(), "addItem");
                Toast.makeText(getActivity(), "Adding Item", Toast.LENGTH_LONG).show();
                break;
        }
    }


    // Method to add a TabHost
    private static void AddTab(FragmentActivity activity, TabHost tabHost, FragmentTabHost.TabSpec tabSpec) {

        tabSpec.setContent(new MyTabFactory(activity));
        tabHost.addTab(tabSpec);
    }

    // Manages the Tab changes, synchronizing it with Pages
    public void onTabChanged(String tag) {
        int pos = this.mTabHost.getCurrentTab();
        this.mViewPager.setCurrentItem(pos);
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    // Manages the Page changes, synchronizing it with Tabs
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        int pos = this.mViewPager.getCurrentItem();
        this.mTabHost.setCurrentTab(pos);
    }

    @Override
    public void onPageSelected(int arg0) {
    }

    private List<Fragment> getFragments(){
        List<Fragment> fList = new ArrayList<Fragment>();

        // TODO Put here your Fragments

        Bundle args = getArguments();
        long id = args.getLong("val");

        ItemList f1 = ItemList.newinstance(id);
        fList.add(f1);

        return fList;
    }


    public class MyPageAdapter extends FragmentStatePagerAdapter {
        private List<Fragment> fragments;

        public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }

    }

}

选项卡内的 ListFragment:

public class ItemList extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

    String DATABASE_TABLE;
    String Query;
    String Order;
    String name;
    MainActivity home;

    View view;
    public static MyListAdapter mAdapter;
    private static Cursor c;



    static ItemList newinstance(long rowId) {
        ItemList itemList = new ItemList();
        // Supply val input as an argument.
        Bundle args = new Bundle();
        args.putLong("val", rowId);
        //args.putString("name", itemName);
        itemList.setArguments(args);
        return itemList;
    }


    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        Bundle args = getArguments();
        int itemId= (int) args.getLong("val");

        mAdapter = new MyListAdapter(getActivity(), R.layout.list_row, c, from, to);


        setListAdapter(mAdapter);
        setListShown(false);

        getLoaderManager().initLoader(itemId, null, this);
    }


        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        public Loader<Cursor> onCreateLoader(int id, Bundle args) {

            // View progressBar = getView().findViewById(R.id.progressbar_loading);
            // progressBar.setVisibility(View.VISIBLE);

            return new RawCursorLoader(getActivity(), Query + Order);
        }

        // Called when a previously created loader has finished loading
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            //View progressBar = getView().findViewById(R.id.progressbar_loading);
            // progressBar.setVisibility(View.GONE);
            // Swap the new cursor in.  (The framework will take care of closing the
            // old cursor once we return.)
            mAdapter.swapCursor(data);

            if (isResumed()) {
                setListShown(true);
            } else {
                setListShownNoAnimation(true);
            }
        }

        // Called when a previously created loader is reset, making the data unavailable
        public void onLoaderReset(Loader<Cursor> loader) {
            // This is called when the last Cursor provided to onLoadFinished()
            // above is about to be closed.  We need to make sure we are no
            // longer using it.
            mAdapter.swapCursor(null);
        }

    }

对话:

public class AddItemDialogFragment extends DialogFragment {   

UpdateItemListener mListener;

public interface UpdateItemsListener {
    public void onItemAdded();
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mListener = (UpdateItemListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement UpdateItemListener");
    }
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Add " + itemName + "?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    postItem(ItemId);
                    mListener.onItemAdded();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                }

            });
    // Create the AlertDialog object and return it
    return builder.create();
}
}
4

1 回答 1

0

我能够弄清楚,我的大脑只是卡住了一段时间。

第一个问题是我使用了 FragmentStatePagerAdapter,它在实例化片段时没有设置标签。我将其设置为这个,因为 FragmentPagerAdapter 有问题,另一个线程建议改为扩展该类。我能够让它与设置标签的 FragmentPagerAdapter 一起工作。然后我在 ItemList 片段的 onAttach() 方法期间调用 getTag() 并在活动上设置变量。然后,当添加项目时,我在 AddItemDialogFragment 上有一个接口,并在 Activity 上有一个侦听器。监听器然后调用:

    ItemList itemList= (ItemList)
            getSupportFragmentManager().findFragmentByTag("Items")
            .getChildFragmentManager().findFragmentByTag("itemListTag");
if(itemList != null) {
    itemList.listChange();
}
于 2013-10-23T03:59:42.527 回答