RecyclerView五步曲:implementation->layout->findViewById->setLayoutManager->setAdapter
1.在build.gradle(Module:app)中加入:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
implementation 'com.android.support:recyclerview-v7:28'
}
2.在布局文件中加入控件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
3.在Activity中获取实例,设置布局,配置数据:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerView);
//设置布局
RecyclerView.LayoutManager layout=new LinearLayoutManager(MainActivity.this);
((LinearLayoutManager) layout).setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layout);
//设置适配器
RecyclerView.Adapter adapter=...
mRecyclerView.setAdapter(adapter);
}
}