3

我有一个带有卡片列表的 RecyclerView。我想知道是否可以在使用手机时将 RecyclerView 的 LayoutManager 更改为线性,在使用平板电脑时以编程方式将其更改为 StaggeredGrid。我最初的想法是在 Activity 上拥有相同的代码,并且只更改 layout.xml,但鉴于 Android 使用不同的 LayoutManager,它似乎比这更复杂。我也尝试使用 Cardslib 库,但对文档感到非常困惑,因为没有自定义卡片的完整示例。有任何想法吗?

4

2 回答 2

3

对的,这是可能的。一种解决方案是在您的 values 文件夹中定义一个布尔资源。例如,您可以定义:

<bool name="is_phone">true</bool>

在你的 values 文件夹和你的 values-sw720dp 和 values-sw600dp 中添加相同的资源并设置为 false。

<bool name="is_phone">false</bool>

然后,在您的 Activity 中onCreate(),您可以执行以下操作:

    boolean isPhone = getResources().getBoolean(R.bool.is_phone);

    if (isPhone) {
        // Set linearlayoutmanager for your recyclerview.
    } else {
        // Set staggeredgridlayoutmanager for your recyclerview.
    }
于 2016-02-06T06:18:47.273 回答
1

所以,正如我告诉@androholic 的那样,我试图弄清楚的是如何根据设备格式改变布局。这样,每当应用程序在平板电脑上加载时,就会显示一个网格,并在手机上显示一个列表。但是,为了使用 RecyclerView 执行此操作,将需要两个 LayouManager:用于列表的 LinearLayoutManager 和 Staggered/GridLayoutManager,这使得代码更加复杂。

我做了什么: 我在一般情况下使用了 GridLayoutManager。我会根据屏幕大小改变的只是列数。这样,一个列表将是一个带有 GridLayoutManager 的 RecyclerView 和 1 列,而一个网格将有多个。就我而言,我只使用 2 列。

我的代码如下。

public class AppListActivity extends AppCompatActivity {

private ArrayList<App> apps;
private int columns;


private String root = Environment.getExternalStorageDirectory().toString();

private boolean isTablet;
private RecyclerViewAdapter rvadapter;

public static Context context;
private SwipeRefreshLayout swipeContainer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getApplicationContext();
    //CHECK WHETHER THE DEVICE IS A TABLET OR A PHONE
    isTablet = getResources().getBoolean(R.bool.isTablet);
    if (isTablet()) { //it's a tablet
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        columns = 2;
    } else { //it's a phone, not a tablet
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        columns = 1;
    }
 //SwipeContainer SETUP
 //ArrayList and RecyclerView initialization
    apps = new ArrayList<App>();

    RecyclerView rv = (RecyclerView) findViewById(R.id.recycler_view);

    rv.setHasFixedSize(true);
    GridLayoutManager gridlm = new GridLayoutManager(getApplicationContext(),columns);
    rv.setLayoutManager(gridlm);
    rvadapter = new RecyclerViewAdapter(apps);
    rv.setAdapter(rvadapter);
    }
    public boolean isTablet() {
       return isTablet;
    }

方法 isTablet 与@androholic 的答案几乎相同。希望这将消除对我的问题是什么(我意识到我的措辞不是最好的)以及我所取得的成就的任何疑问。

于 2016-02-07T19:39:21.413 回答