创建一个layout

显示天气预报的列表我们使用RecyclerView,所以你需要在build.gradle中增加一个新的依赖:

1. dependencies {
2. compile fileTree(dir: 'libs', include: ['*.jar'])
3. compile "com.android.support:appcompat-v7:$support_version"
4. compile "com.android.support:recyclerview-v7:$support_version" ...
5. }

然后,activity_main.xml如下:

1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. android:layout_width="match_parent"
3. android:layout_height="match_parent">
4. <android.support.v7.widget.RecyclerView
5. android:id="@+id/forecast_list"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"/>
8. </FrameLayout>

在Mainactivity.kt中删除掉之前用来测试的能正常运行的所有代码(现在应该会提示错误)。暂且我们使用老的findViewByid()的方式:

1. val forecastList = findViewById(R.id.forecast_list) as RecyclerView
2. forecastList.layoutManager = LinearLayoutManager(this)

如你所见,我们定义类一个变量并转型为RecyclerView。这里与Java有点不同,我们会在下一章分析这些不同之处。LayoutManager会通过属性的方式被设置,而不是通过setter,这个layout已经足够显示一个列表了。

对象实例化

对象实例化也是与Java中有些不同。如你所见,我们去掉了new关键字。这时构造函数仍然会被调用,但是我们省略了宝贵的四个字符。LinearLayoutManager(this)创建了一个对象的实例。