【问题标题】:getListView() replacement when using RecyclerView使用 RecyclerView 时的 getListView() 替换
【发布时间】:2015-08-10 13:04:09
【问题描述】:

我正在我的应用程序中实现 Material Design 并将 ListViews 转换为 RecyclerViews。我一直在关注使用 getListView() 方法的教程,但是当我使用 AppCompatActivity 扩展我的类时,这些教程不再可用。我可以使用其他替代方法吗?

【问题讨论】:

  • getListView() 方法可用于 ListActivity , ListFragment 返回列表视图。要替换此类实例,只需将 recyclerview 放在 AppCompatActivity 中并使用它。

标签: java android material-design


【解决方案1】:

getListView()ListActivityListFragment 上的便捷方法。但是,使用ListView 不需要使用ListActivityListFragment。如果您使用常规的Activity 或常规的Fragment,您将使用findViewById() 从您的布局中检索您的ListView,就像使用任何其他类型的小部件一样。

RecyclerView 也是如此。您将使用 findViewById() 从膨胀的布局中检索 RecyclerView

现在,欢迎您创建自己的 RecyclerViewActivityRecyclerViewFragment,如果您愿意,您可以扩展它们。例如,您可以有这样的RecyclerViewActivity

/***
 Copyright (c) 2008-2015 CommonsWare, LLC
 Licensed under the Apache License, Version 2.0 (the "License"); you may not
 use this file except in compliance with the License. You may obtain    a copy
 of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
 by applicable law or agreed to in writing, software distributed under the
 License is distributed on an "AS IS" BASIS,    WITHOUT WARRANTIES OR CONDITIONS
 OF ANY KIND, either express or implied. See the License for the specific
 language governing permissions and limitations under the License.

 From _The Busy Coder's Guide to Android Development_
 https://commonsware.com/Android
 */

package com.commonsware.android.recyclerview.simplelist;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;

public class RecyclerViewActivity extends Activity {
  private RecyclerView rv=null;

  public void setAdapter(RecyclerView.Adapter adapter) {
    getRecyclerView().setAdapter(adapter);
  }

  public RecyclerView.Adapter getAdapter() {
    return(getRecyclerView().getAdapter());
  }

  public void setLayoutManager(RecyclerView.LayoutManager mgr) {
    getRecyclerView().setLayoutManager(mgr);
  }

  public RecyclerView getRecyclerView() {
    if (rv==null) {
      rv=new RecyclerView(this);
      rv.setHasFixedSize(true);
      setContentView(rv);
    }

    return(rv);
  }
}

这里可以使用getRecyclerView()RecyclerViewActivity会为你创建RecyclerView实例,并将其设置为活动的内容视图。虽然在我的例子中,RecyclerViewActivity 继承自 Activity,但将其更改为从 AppCompatActivity 继承只需向基类添加 9 个字符(Activity --> AppCompatActivity)。

【讨论】:

  • 谢谢@CommonsWare。我现在明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多