728x90

<전체 과정 요약>

 

1. implementation 'com.android.support:recyclerview-v7:28.0.0'  종속성추가

 

2. main.xml에 button을 생성해주고 버튼클릭시 activity_news.xml로 이동

 

3. activity_news.xml에는 Recyclerviewlayout컴포넌트가 배치

 

3. newsactivity.class가 실행되고 activity_news.xml에서 recyclerviewlayout 을 가져옴

 

4. newsactivity.class -> setadapter() -> activity_news.xml 과 adapter(myadapter) 매칭

 

5. adapter - oncreateviewholder 함수 & myviewholder class -  component들을 관리 

 

6. adapter생성장에 데이터를 전송할수있는 장치를 만들어주어 activity_news.xml -> adapter -> row_new.xml 데이터 전송

 

 

<activity_news.xml>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
   
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </androidx.recyclerview.widget.RecyclerView>
    
    
</LinearLayout>

activity_news.xml에 id를 부여하였고 width,height 는 match로 설정함

 

 

<row_news.xml>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <!--뉴스 이미지를 넣을 것-->
            <ImageView
                android:id="@+id/ImageView_news"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:src="@drawable/ic_launcher_background"></ImageView>
            <!-- 뉴스의 제목을 넣을 공간 -->
            <TextView
                android:id="@+id/TextView_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Hello, this is example of RecycleView"
                android:layout_alignBottom="@+id/ImageView_news"
                android:textSize="20dp"
                android:background="#77ff88aa"
                ></TextView>
        </RelativeLayout>
        <!--뉴스의 내용 일부를 적을 공간-->
        <TextView
            android:id="@+id/TextView_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Contents part"
            android:textSize="15dp"
            android:ellipsize="end"
            ></TextView>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

recyclerview에 들어가는 아이템뷰 각항목의 디자인을

이미지,텍스트뷰(제목),텍스트뷰(내용)으로 설정해주었음

 

<NewsActivity.class> matched with activity_news.xml

 

package com.example.news1124;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


public class NewsActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;
    /* 리스트의 각 객체들에 들어갈 데이터들 / DB로부터 또는 사용자로부터 받아올 수 있다 */
    private String[] myDataset = {"첫 번째 뉴스의 제목 ","두 번째 뉴스의 제목","세 번째 뉴스의 제목"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* matching with activity_news*/
        setContentView(R.layout.activity_news);

        /* activity_news.xml에서 RecyclerView 가져옴 */
        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        /* Adapter를 연결 !
           Adapter를 사용해서 리스트의 각 항목들을 효과적으로 관리 */
        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(myDataset); // Adapter생성자를 사용 해당 생성자는 Myadapter.class에서 확인
        recyclerView.setAdapter(mAdapter);

    }
}

setContentview(R.layout.activity_news) 를 통해 레이아웃을 activity_news.xml과 매칭시켜줌

 

recyclerview 를 findview를통해 연결해주고

 

recyclerview.setHasFixedSize()에 true값을 줌으로써  RecyclerView의 레이아웃 크기는 변경되지 않음

 

layoutManager = new LinearLayoutManager(this); 레이아웃매니저 생성

 

recyclerview.setLayoutmanager(layoutmanger)을통해 recyclerview에 레이아웃매니저 지정

 

madapter = new myadapter(mydataset);  

 

recyclerview.setadapter()을 통해 recyclerview에 어뎁터 지정

 

 

MyAdapter.class

 

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private String[] mDataset;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder

    /* 리스트 내의 각 항목들을 관리하는 ViewHolder class*/

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView TextView_title;
        public TextView TextView_content;
        public ImageView ImageView_news;

        /* 가져오는 layout에서 id값을 통해 해당 Component를 가져와 변수에 저장 */
        public MyViewHolder(View v) {
            super(v);
            TextView_title = v.findViewById(R.id.TextView_title);
            TextView_content = v.findViewById(R.id.TextView_content);
            ImageView_news = v.findViewById(R.id.ImageView_news);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    /* NewsActivity에서 Adapter와 매칭시 사용하는 사용자이다
       이 때 NewsActivity의 데이터들이 데이터배열을 통해 전달되어진다
    */

    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        /* 리스트의 각 항목에 입혀줄 디자인을 생성한다 즉, create a new view
           setContentView(R.layout.xxx) 처럼 xml 매칭, 하지만 RecycleView의 특정 부분만 변경시킬 때는
           효율성을 위해 inflate함수를 사용
           사용할 xml(row_news)의 최상위 layout을 이용
         * */
        androidx.constraintlayout.widget.ConstraintLayout v
                = (androidx.constraintlayout.widget.ConstraintLayout) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_news, parent, false);

        MyViewHolder vh = new MyViewHolder(v); /* row_news에서 components를 가져와 MyViewHolder객체의 변수들에 저장된다*/
        return vh;
    }

    // Replace the contents of a view (값 대입)
    @Override

    /* MyAdapter.class와 매칭되어있는 row_news.xml에 있는 TextView_title 컴포넌트에 값 SET */
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        // TextView_title component에 값을 지정한다 NewsActivity.class에서 넘어온 mDataset에 있는 데이터
        holder.TextView_title.setText(mDataset[position]);

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

 

++

build.gradle(app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion "30.0.2"
    defaultConfig {
        applicationId "com.example.news1124"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.3.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'


}

 

실시간 뉴스앱을 만들고싶다면

이부분에서 okhttp를 통해 json데이터를 잘 다뤄주면 될거같다.

이미지관리 fresco를 통해 이미지를 가져와주고

728x90

+ Recent posts