0
点赞
收藏
分享

微信扫一扫

Android 系列 6.13使用卡片小部件


6.13使用卡片小部件
问题
卡小部件是一种相对较新的UI控件形式,您想要了解何时以及如何使用它们。

当你想要一个漂亮的边框的自包含视图组时,使用一个卡,通常很多在ListView或RecyclerView。
讨论
Card是一个新的ViewGroup,子类化FrameLayout,提供边框和阴影。
它是兼容性包的一部分,以便它可以与旧版本以及新版本的Android一起使用。卡很容易使用,只要你记得它是一个FrameLayout(参见在配方6.3中的FrameLayout的讨论)。直接放在FrameLayout中的项目显示在堆栈中,如果它们是不同的大小,则各个部分的一部分将可见。在我们的示例中,这是从一个假设的房地产房源列表项目,我们放置一个照片(ImageView)的RelativeLayout和一些描述性文本(TextView)在一张卡,并将卡放置在我们的主布局。
我们使用默认阴影和边框设置,但覆盖大小和角半径。卡的布局文件如示例6-20所示。
实例6-20。卡片的布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="300dp"
android:layout_height="340dp"
card_view:cardCornerRadius="6dp"
tools:context="com.androidcookbook.carddemo.CardActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/house_front_view"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/house_descr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>

显示此卡布局的代码仅填充一个卡(请参见示例6-21),但是很容易将其转换为适用于ListView或RecyclerView的适配器,并且布局文件也已经适合此类使用。


实例6-21。卡的Java安装程序



public class CardActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.card_layout);
// Dynamically set the image and text
ImageView img = (ImageView) findViewById(R.id.house_front_view);
Drawable d = ContextCompat.getDrawable(this,R.drawable.fixer_upper_1);
img.setImageDrawable(d);
TextView descr = (TextView) findViewById(R.id.house_descr);
descr.setText("Beautiful fixer-upper! Only used on weekends by respectable Hobbit couple!");
}
}

这几行代码的结果可以在图6-10中看到。


举报

相关推荐

0 条评论