安卓ListView在行末添加文本。

问题描述 投票:1回答:2

我的ListView要显示的是用户的等级,用户名,以及他们的分数,比如。1. John 25和我想显示分数,就像附件中的例子一样,我的ListView是要显示用户、用户名和他们的分数,比如:1.

enter image description here

java android android-studio listview user-interface
2个回答
1
投票

你需要使用的是一个 CustomAdapter 而不是默认的适配器。请参考其他答案 列表视图的自定义适配器

基本上,你可以创建自己的项目布局:你希望列表中的每个项目如何显示(可以用一个TextView显示用户名,另一个TextView显示分数)。

然后在 getView 方法来设置每一个的值。


1
投票

你可以使用自定义列表适配器和自定义布局xml来实现这一点。

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = findViewById(R.id.list_view);
    listView.setAdapter(new NameRankAdapter(this));
}
}

NameRankAdapter.java

public class NameRankAdapter extends BaseAdapter {
private Context context;

public NameRankAdapter(Context context) {
    this.context = context;
}

@Override
public int getCount() {
    return 20;
}

@Override
public Object getItem(int i) {
    return i;
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    if (view == null) {
        view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
    }
    TextView name = view.findViewById(R.id.name);
    name.setText("Name " + i);
    TextView rank = view.findViewById(R.id.rank);
    rank.setText(String.valueOf(i));
    return view;
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".MainActivity">

<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout>

List_item.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:text="name"
    android:id="@+id/name"
    android:textSize="30sp"
    android:textColor="@android:color/black"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:text="name"
    android:textSize="25sp"
    android:id="@+id/rank"
    android:textColor="@android:color/black"/>
</FrameLayout>
© www.soinside.com 2019 - 2024. All rights reserved.