我正在尝试在包含可显示图像的可按按钮的活动上创建列表视图。但是,我遇到了创建纯文本列表视图的问题。我的代码编译正确,但在手机上运行时,当我点击打开活动时它会崩溃。我错过了我的代码中的重要内容,还是忘记在其他地方添加内容?
public class druglist extends AppCompatActivity {
String[] fulldruglist = {"Aspirin","Acetaminophen","Activated Charcoal","Adenosine",
"Afrin","Albuterol","Amiodarone","Aspirin"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_druglist);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_druglist, fulldruglist);
ListView listView = (ListView) findViewById(R.id.druglistview);
listView.setAdapter(adapter);
}}
答案 0 :(得分:0)
这就是你的问题:
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_druglist, fulldruglist);
此处您需要提供的布局是用于项目的布局。 但是你上面有两行:
setContentView(R.layout.activity_druglist);
说您提供的布局是用于容器的布局
我们假设您在布局R.layout.activity_druglist
中定义了列表,并且您在布局R.layout.activity_druglist_item
中定义了列表中每个条目的布局,您应该写道:
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_druglist_item, fulldruglist);
更新:以下是一些显示列表视图的简约代码:
<强> MainActivity.java :
public class MainActivity extends AppCompatActivity {
private ListView myListView;
String[] fulldruglist = {"Aspirin","Acetaminophen","Activated Charcoal",
"Adenosine", "Afrin","Albuterol","Amiodarone","Aspirin"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myListView = findViewById(R.id.myListView);
ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.item,
R.id.textView, fulldruglist);
myListView.setAdapter(adapter);
}
}
<强> activity_main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<ListView
android:id="@+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
<强> item.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text" />
</android.support.constraint.ConstraintLayout>
activity_main
是包含listview
item
是单元格内容的布局
textView
是TextView
,用于显示fulldruglist
的每个条目