非空构造函数问题

时间:2014-04-06 18:26:12

标签: android android-fragments constructor android-listfragment android-tabs

我试图创建一个非空构造函数,但没有成功。 日食说:

从Fragment文档中: 每个片段都必须有一个空构造函数,因此可以在恢复其活动状态时进行实例化。强烈建议子类没有其他构造函数 带参数,因为在重新实例化片段时不会调用这些构造函数;相反,参数可以由调用者使用setArguments(Bundle)提供,稍后由Fragment使用getArguments()检索。

那么如何创建非空构造函数呢? 这是代码:

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;


public class MyListFragment extends ListFragment implements
    LoaderCallbacks<Void> {

private static final String TAG = "FragmentTabs";

private String mTag;
private MyAdapter mAdapter;
private ArrayList<String> mItems;
private LayoutInflater mInflater;
private int mTotal;
private int mPosition;

private static final String[] About = { "Lorem", "ipsum", "dolor", "sit",
        "amet", "consectetur", "adipiscing", "elit", "Fusce", "pharetra",
        "luctus", "sodales" };
private static final String[] FAQ = { "I", "II", "III", "IV", "V",
        "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV" };
private static final String[] Tips = { "hello" , "bitch" , "ass" , "partners" , "screw", "you" ,"all", "peace" , "out"};

private static final int SLEEP = 1000;

private final int wordBarColor = R.color.word_bar;
private final int numberBarColor = R.color.number_bar;



public MyListFragment(String tag) {
    mTag = tag;
    mTotal = HelpFragment.TAB_About.equals(mTag) ? About.length
            : About.length;

    Log.d(TAG, "Constructor: tag=" + tag);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // this is really important in order to save the state across screen
    // configuration changes for example
    setRetainInstance(true);

    mInflater = LayoutInflater.from(getActivity());

    // you only need to instantiate these the first time your fragment is
    // created; then, the method above will do the rest
    if (mAdapter == null) {
        mItems = new ArrayList<String>();
        mAdapter = new MyAdapter(getActivity(), mItems);
    }
    getListView().setAdapter(mAdapter);

    // initiate the loader to do the background work
    getLoaderManager().initLoader(0, null, this);
}

@Override
public Loader<Void> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) {

        @Override
        public Void loadInBackground() {
            try {
                // simulate some time consuming operation going on in the
                // background
                Thread.sleep(SLEEP);
            } catch (InterruptedException e) {
            }
            return null;
        }
    };
    // somehow the AsyncTaskLoader doesn't want to start its job without
    // calling this method
    loader.forceLoad();
    return loader;
}

@Override
public void onLoadFinished(Loader<Void> loader, Void result) {

    // add the new item and let the adapter know in order to refresh the
    // views
    mItems.add(HelpFragment.TAB_About.equals(mTag) ? About[mPosition]
            : FAQ[mPosition]);
    mAdapter.notifyDataSetChanged();

    // advance in your list with one step
    mPosition++;
    if (mPosition < mTotal - 1) {
        getLoaderManager().restartLoader(0, null, this);
        Log.d(TAG, "onLoadFinished(): loading next...");
    } else {
        Log.d(TAG, "onLoadFinished(): done loading!");
    }
}

@Override
public void onLoaderReset(Loader<Void> loader) {
}

private class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, List<String> objects) {
        super(context, R.layout.list_item, R.id.text, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        Wrapper wrapper;

        if (view == null) {
            view = mInflater.inflate(R.layout.list_item, null);
            wrapper = new Wrapper(view);
            view.setTag(wrapper);
        } else {
            wrapper = (Wrapper) view.getTag();
        }

        wrapper.getTextView().setText(getItem(position));
        wrapper.getBar().setBackgroundColor(
                mTag == HelpFragment.TAB_About ? getResources().getColor(
                        wordBarColor) : getResources().getColor(
                        numberBarColor));
        return view;
    }

}

// use an wrapper (or view holder) object to limit calling the
// findViewById() method, which parses the entire structure of your
// XML in search for the ID of your view
private class Wrapper {
    private final View mRoot;
    private TextView mText;
    private View mBar;

    public Wrapper(View root) {
        mRoot = root;
    }

    public TextView getTextView() {
        if (mText == null) {
            mText = (TextView) mRoot.findViewById(R.id.text);
        }
        return mText;
    }

    public View getBar() {
        if (mBar == null) {
            mBar = mRoot.findViewById(R.id.bar);
        }
        return mBar;
    }
}
}

感谢U.

提供的任何帮助

1 个答案:

答案 0 :(得分:1)

  

那么如何创建非空构造函数呢?

通常,您不会在Fragment上创建非空构造函数。而是使用工厂模式,如评论中所述:

  static EditorFragment newInstance(int position) {
    EditorFragment frag=new EditorFragment();
    Bundle args=new Bundle();

    args.putInt(KEY_POSITION, position);
    frag.setArguments(args);

    return(frag);
  }

然后,您的片段可以通过Bundle检索getArguments(),并且您可以检索放入Bundle的任何数据。