本文是在上一篇文章的基础上做的修改:android中RecyclerView控件的使用
1、修改列表项news_item.xml:我这里是把新闻标题挪到了新闻图片的下面显示
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="150dp"
android:layout_height="match_parent"
android:minWidth="400dp"> <ImageView
android:id="@+id/newsPic"
android:layout_width="match_parent"
android:layout_height="80dp"
android:adjustViewBounds="false"
android:src="@drawable/o1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" /> <TextView
android:id="@+id/newsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="TextView"
app:layout_constraintTop_toBottomOf="@+id/newsPic" />
</android.support.constraint.ConstraintLayout>
2、修改MainActivity.java类,注意红色添加的内容,其他内容都没有变:
package com.example.chenrui.app1; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout; import com.example.chenrui.common.News; import java.util.ArrayList;
import java.util.List; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); List<News> newsList = new ArrayList();
newsList.add(new News("新闻标题1",R.drawable.o1));
newsList.add(new News("新闻标题2",R.drawable.o2));
newsList.add(new News("新闻标题3",R.drawable.o3));
newsList.add(new News("新闻标题4",R.drawable.o4));
newsList.add(new News("新闻标题5",R.drawable.o5));
NewsAdapter newsAdapter = new NewsAdapter(newsList); RecyclerView view = findViewById(R.id.list1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
view.setLayoutManager(layoutManager);
view.setAdapter(newsAdapter);
}
}
最终的展示效果: