根据设备格式更改LayoutManager

3
我有一个带卡片列表的 RecyclerView。 我想知道是否可能在使用电话时将 RecyclerView 的 LayoutManager 以编程方式更改为线性布局,并在使用平板电脑时更改为瀑布流布局。 我的初始想法是在 Activity 上使用相同的代码,仅更改 layout.xml,但由于 Android 使用不同的 LayoutManagers,因此它似乎不那么简单。 我还尝试使用 Cardslib 库,但是由于没有自定义卡片的完整示例,因此文档使我非常困惑。 有任何想法吗?
2个回答

3

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

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

在您的值文件夹中以及您的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.
    }

这只是答案的一部分。我发现可以使用相同的LayoutManager(Grid),并根据设备更改列。因此,如果我有手机,则显示相同的网格但仅有一列(实际上是制作列表而不是网格),当它是平板电脑时则有更多列。我找到时间后会相应地编写答案。编辑:忘记说谢谢了,所以,谢谢! - Hugo M. Zuleta

1
所以,正如我告诉@androholic的那样,我试图弄清楚的是如何根据设备格式更改布局。这样,每当应用程序在平板电脑上加载时,就会显示网格,而在手机上则显示列表。 但是,为了使用RecyclerView实现这一点,需要两个LayouManager:列表的LinearLayoutManager和Staggered/GridLayoutManager,使代码变得更加复杂。
我所做的是: 我为通用情况使用了GridLayoutManager。根据屏幕大小更改的只是列数。这样,列表将是具有1列的GridLayoutManager的RecyclerView,而网格将具有多个列。在我的情况下,我只使用了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 的 答案 上的方法基本相同。希望这能消除任何对我的问题(我意识到我的措辞不是最好的)以及我的成就存在疑虑的疑虑。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接