【问题标题】:Android ListView add text to the end of rowAndroid ListView 将文本添加到行尾
【发布时间】:2020-08-02 22:15:57
【问题描述】:

我的 ListView 会显示用户的排名、用户名和他们的分数,例如:1. John 25 我想显示分数,就像附件示例中显示的那样。

【问题讨论】:

标签: java android android-studio listview user-interface


【解决方案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>

【讨论】:

    【解决方案2】:

    您需要使用CustomAdapter 而不是默认适配器。请参考这个其他答案Custom Adapter for List View

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多