RecyclerView不执行方法

时间:2018-04-30 09:49:46

标签: java android android-recyclerview

经过长时间的研究和尝试与错误之后,我无法理解为什么在创建getItemCount()之后我的RecyclerView没有被调用。

向您介绍我的代码,简短说明:

基本上,我的RecyclerView的第一次创建是空的,因为数据尚未准备好,但片段是通过setContentView()调用创建的。然后第二轮开始,创建一个从URL获取数据的Loader。之后,会创建一个新的NewsEntryFragment,作为回报,会创建一个新的RecyclerViewAdapter,该SpinnerActivity应显示在我的getItemCount()中。

我调试了几次并整理了一些东西:

  • getItemCount()在第一轮被召唤4次,空轮。它总是返回0,但这很好,因为无论如何都没有数据。
  • onBindViewHolder()永远不会在第二轮中被调用,其中数据最终准备好并且应该显示。
  • 无论是在第一轮还是在第二轮,
  • RecyclerView都不会被召唤一次。

也许,这是因为public class SpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, LoaderManager.LoaderCallbacks<List<NewsEntry>>, NewsEntryFragment.OnListFragmentInteractionListener, NewsEntryFragment.DataInterface { final String GUARDIAN_BASE_URL = "http://content.guardianapis.com/search?api-key=xxx"; final String PARAM_SORT = "order-by"; final String PARAM_QUERY = "q"; final String PARAM_CURRENT_PAGE = "page"; final String PARAM_SHOW_FIELDS = "show-fields"; private String mQuery; public URL mRequestURL = null; LoaderManager loaderManager = getLoaderManager(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); private ArrayList<NewsEntry> mNewsEntries = new ArrayList<>(); private final String TAG = "MY"; ArrayList<String> mTopicsList = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= 21) { getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); } populateSpinner(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mQuery = parent.getItemAtPosition(position).toString(); buildQuery(); loaderManager.destroyLoader(0); Loader loader = loaderManager.initLoader(0, null, this); } @Override public void onNothingSelected(AdapterView<?> parent) { } @Override public Loader<List<NewsEntry>> onCreateLoader(int id, Bundle args) { Log.i("MY", "onCreateLoader: Loader created"); return new NewsLoader(this, mRequestURL); } @Override public void onLoadFinished(Loader<List<NewsEntry>> loader, List<NewsEntry> fetchedNewsEntries) { mNewsEntries.addAll(fetchedNewsEntries); //NewsEntryFragment fragment = (NewsEntryFragment) fragmentManager .findFragmentById(R.id.headlines_fragment); fragmentTransaction.add(new NewsEntryFragment(), ""+mQuery+" used for this Fragment") .commit(); Log.i(TAG, "onLoadFinished: " + mQuery + " used for this Fragment"); } @Override public void onLoaderReset(Loader<List<NewsEntry>> loader) { } @Override public void onListFragmentInteraction(NewsEntry item) { } private void populateSpinner(){ ArrayList<String> topics = new ArrayList<>(); topics.add("Android"); topics.add("Android"); topics.add("Test 3"); Spinner spinner = findViewById(R.id.toolbar_spinner); ArrayAdapter<String> topicsAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, topics); topicsAdapter.setDropDownViewResource(R.layout.spinner_dropdown); spinner.setAdapter(topicsAdapter); spinner.setOnItemSelectedListener(this); } } 被创建了两次?第二次,事情不被称为?我不知道......这就是我需要你帮助的原因:)。

无论如何,这是我的代码:

SpinnerActivity.java

public class NewsEntryFragment extends Fragment {

private static final String ARG_COLUMN_COUNT = "column-count";
private static ArrayList<NewsEntry> mNewsEntries = new ArrayList<>();
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
Context mContext;

private final String TAG = "MY";

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public NewsEntryFragment() {
}

public interface DataInterface{

    ArrayList<NewsEntry> getNewsEntriesInterface();

}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
    }
}


@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_newsentry_list, container, false);

    try {
        ArrayList<NewsEntry> newsEntries = 
((DataInterface)mContext).getNewsEntriesInterface();
        mNewsEntries.addAll(newsEntries);
        Log.i("MY", "onCreateView ArrayList newsEntries.size = "+newsEntries.size());
    } catch (Exception e){
        e.printStackTrace();
    }

    RecyclerView recyclerview = (RecyclerView) view;
    MyNewsEntryRecyclerViewAdapter adapter = 
new MyNewsEntryRecyclerViewAdapter(mNewsEntries, mListener);
    recyclerview.setAdapter(adapter);
    recyclerview.setLayoutManager(new LinearLayoutManager(view.getContext()));

    return view;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
    if (context instanceof OnListFragmentInteractionListener) {
        mListener = (OnListFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnListFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

NewsEntryFragment.java

public class MyNewsEntryRecyclerViewAdapter extends
 RecyclerView.Adapter<MyNewsEntryRecyclerViewAdapter.ViewHolder> {

private final List<NewsEntry> mNewsEntry;
private final OnListFragmentInteractionListener mListener;


public MyNewsEntryRecyclerViewAdapter
(List<NewsEntry> newsEntries, OnListFragmentInteractionListener mListener) {
    mNewsEntry = newsEntries;
    this.mListener = mListener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.fragment_newsentry, parent, false);
    return new ViewHolder(view);
}



@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.mItem = mNewsEntry.get(position);
    holder.mIdView.setRadius(26);
    Picasso.get().load(mNewsEntry.get(position)
           .getmThumbnail()).into(holder.mNewsThumbnail);


    holder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (null != mListener) {
                // Notify the active callbacks interface (the activity, if the
                // fragment is attached to one) that an item has been selected.
                mListener.onListFragmentInteraction(holder.mItem);
            }
        }
    });
}

@Override
public int getItemCount() {
    return mNewsEntry.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public final View mView;
    public final CardView mIdView;
    public final ImageView mNewsThumbnail;
    public NewsEntry mItem;

    public ViewHolder(View view) {
        super(view);
        mView = view;
        mIdView = (CardView) view.findViewById(R.id.card_view);
        mNewsThumbnail = (ImageView) view.findViewById(R.id.news_thumbnail);
    }


}

MyNewsEntryRecyclerViewAdapter.java

    var documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    documentsPath.append("/filescheme/filescheme/images/3.png")
    let url = URL(fileURLWithPath: documentsPath)
    do {
        let imageData = try Data.init(contentsOf: url)
        let image = UIImage(data: imageData)
    } catch {
        print(error.localizedDescription)
    }

0 个答案:

没有答案