这是我第一次在这里提问。抱歉,如果我说错了,请原谅我在编程方面缺乏经验。
我一直在使用this网站创建一个Listview,它显示“Character”对象的“name”和“level”属性。但是,出于某种原因,名称和级别永远不会出现,如here所示。我想解决这个问题。
这是我的MainActivity:
package com.example.laptoproeland.mydndproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Character> arrayOfCharacters = new ArrayList<>();
arrayOfCharacters.add(new Character("Styx", 6));
arrayOfCharacters.add(new Character("Gulthrak", 1));
arrayOfCharacters.add(new Character("Edmund", 4));
arrayOfCharacters.add(new Character("K'naan", 3));
arrayOfCharacters.add(new Character("Helga", 1));
CharactersAdapter adapter = new CharactersAdapter(this, arrayOfCharacters);
ListView listView = (ListView) findViewById(R.id.listViewMain);
listView.setAdapter(adapter);
}
}
这是我的适配器:
package com.example.laptoproeland.mydndproject;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CharactersAdapter extends ArrayAdapter<Character> {
public CharactersAdapter(Context context, ArrayList<Character> arrayOfCharacters) {
super(context, 0, arrayOfCharacters);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Character character = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.character_item, parent, false);
}
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvLevel = (TextView) convertView.findViewById(R.id.tvLevel);
tvName.setText(character.name);
tvLevel.setText(String.valueOf(character.level));
return convertView;
}
}
这是我的character_item:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"
android:textSize="30sp"
android:textStyle="normal|bold" />
<TextView
android:id="@+id/tvLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/level"
android:layout_marginStart="10dp"
android:textSize="30sp" />
</LinearLayout>
如果需要任何其他信息或代码来解决此问题,请告诉我。谢谢。