我正在尝试使用ArrayAdapter创建自定义列表视图,每行显示一个Image& TextView中。我使用以下代码,但应用程序无法运行:
package demo.android.listviewadapter;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String[] buzzWords = {"Buzz-1", "Buzz-2", "Buzz-3", "Buzz-4", "Buzz-5", "Buzz-6", "Buzz-7"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout, R.id.txtName, buzzWords));
}
@Override
public void onListItemClick (ListView parent, View v, int position, long id) {
Toast.makeText(this, "You Clicked: " + buzzWords [position], Toast.LENGTH_SHORT).show();
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imgName"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@+id/txtName"
/>
</LinearLayout>
activity_main.xml
是映射到MainActivity
的布局文件。但是,我在分配适配器时使用custom_layout.xml
文件来自定义布局。请有人告诉我我做错了什么?提前谢谢。
答案 0 :(得分:3)
答案 1 :(得分:2)
缺少
setContentView(R.layout.activity_main);
进入onCreate方法
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout, R.id.txtName, buzzWords));
}
还有..
进入activity_main.xml
将@+id/android:list
替换为@android:id/list
答案 2 :(得分:0)
将自定义布局更改为
的 customlayout.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="30sp" >
</TextView>
并改变这个
setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout, R.id.txtName, buzzWords));
在OnCreate
方法中
setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout,buzzWords));