ListView ArrayAdapter Android được áp dụng khá phổ biến trong android studio hiện nay việc muốn hiển thị một loạt các danh sách thông tin về một sản phẩm hoặc thông tin nào đó thì bạn hoàn toàn có thể sử dụng ListView qua bài viết sau.

Nếu bạn chưa cài đặt Android Studio thì bạn có thể tải Android Studio Tại Đây.

Trong file Activity_main.xml các bạn thêm đoạn code sau.

    <ListView

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Để hiển thị được danh sách của sản phẩm trong ListView thì bạn cần tạo một id cho ListView đó.

Code ListView đầy đủ.

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Trong mục layout các bạn tạo mới một File style_layout.xml như sau.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    android:textSize="20dp"
    android:textStyle="normal" />

Ở File MainActivity.java các bạn khai báo các giá trị sau.

ListView listView;
    String[] strings = {"Menu 1","Menu 2","Menu 3","Menu 4","Menu 5","Menu 6","Menu 7","Menu 8","Menu 9"};
    ArrayAdapter adapter;

 Xem thêm: Border Bottom Layout Android Studio ?

Trong hàm protected  onCreate của file MainActivity.java thêm các giá trị sau.

listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<String>MainActivity.this,R.layout.style_layout,strings);
        listView.setAdapter(adapter);

Code File MainActivity.java đầy đủ như sau.

import androidx.appcompat.app.AppCompatActivity;


import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class MainActivity extends AppCompatActivity {
    ListView listView;
    String[] strings = {"Menu 1","Menu 2","Menu 3","Menu 4","Menu 5","Menu 6","Menu 7","Menu 8","Menu 9"};
    ArrayAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(MainActivity.this,R.layout.style_listview,strings);
        listView.setAdapter(adapter);

    }

}

Hình ảnh ListView ArrayAdapter Android Studio.

ListView ArrayAdapter Android Studio
76 / 100

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *