Android 无法在ArrayAdapter中使用自定义布局
我是android新手,我想使用我的自定义布局文件,而不是简单的列表项,但它不允许这样做。我想向列表中的每个项目添加背景图像(在layout->custom_view.xml中定义),或者帮助我设置整个页面的背景,在下面的代码中,我应该在哪里使用setContentView方法。另外,如果要在下面的.xml文件中进行任何更改,请告诉我Android 无法在ArrayAdapter中使用自定义布局,android,xml,Android,Xml,我是android新手,我想使用我的自定义布局文件,而不是简单的列表项,但它不允许这样做。我想向列表中的每个项目添加背景图像(在layout->custom_view.xml中定义),或者帮助我设置整个页面的背景,在下面的代码中,我应该在哪里使用setContentView方法。另外,如果要在下面的.xml文件中进行任何更改,请告诉我 public class Planet extends ListActivity { @Override public void onCreate
public class Planet extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
//setContentView(R.layout.custom_view); Tried to set the view from here but the application is crashing...
String[] planet_names = new String[] {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Sun"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, planet_names);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position == 0)
{
Intent myIntent = new Intent(Planet.this, Galaxy.class);
startActivityForResult(myIntent, 0);
}
}
});
}
公共类活动{
@凌驾
public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);
//setContentView(R.layout.custom_视图);试图从此处设置视图,但应用程序正在崩溃。。。
字符串[]行星名称=新字符串[]{“水星”、“金星”、“地球”、“火星”、“木星”、“土星”、“天王星”、“海王星”、“太阳”};
ArrayAdapter=新的ArrayAdapter(这是android.R.layout.simple\u list\u item\u 1,planet\u名称);
setListAdapter(适配器);
ListView lv=getListView();
lv.setTextFilterEnabled(真);
lv.setOnItemClickListener(新的OnItemClickListener(){
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
如果(位置==0)
{
Intent myIntent=新Intent(Planet.this,Galaxy.class);
startActivityForResult(myIntent,0);
}
}
});
}
自定义_view.xml文件如下所示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
您不需要在ListActivity
中设置contentview。ListActivity
已经为您设置了。如果您想自定义布局,请使用活动。您需要在设置contentview()之前调用super.onCreate()
。如果要在ListActivity中使用自定义布局,则需要为ListView提供id@android:id/list
,只需使用此选项即可
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.yourcustomview_withonetextview,R.id.yourcustomlayouttextviewid, planet_names);
ArrayAdapter adapter=new ArrayAdapter(这个,R.layout.yourcustomview\u带有一个extview,R.id.yourcustomlayoutextview\u名称);