gpt4 book ai didi

java - ListView 导致 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 13:06:32 26 4
gpt4 key购买 nike

这是我的第一个 Android 应用程序,我正在尝试放置一个 ListView ,并且我已经遵循了许多教程,但我总是得到相同的结果,启动应用程序时崩溃。

XML

<RelativeLayout 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"
android:background="@drawable/background"
android:gravity="top"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mattigins.mediacenter.MainActivity$PlaceholderFragment" >

<View
android:id="@+id/view1"
android:layout_width="550dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/View01"
android:background="@drawable/semi_trans_box" />

<View
android:id="@+id/View01"
android:layout_width="550dp"
android:layout_height="wrap_content"
android:layout_marginRight="58dp"
android:layout_toLeftOf="@+id/view1"
android:background="@drawable/semi_trans_box" />

<ListView
android:id="@+id/List1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/View01"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/View01" >

</ListView>

代码

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}

ListView listView = (ListView) findViewById(R.id.List1);
String[] test_items = {"1","2","3","4"};
ArrayAdapter<String> test_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test_items);
listView.setAdapter(test_adapter);

}

最佳答案

看起来您的ListView属于Fragment布局。正在查看

FragmentonCreateView中。

ListView listView = (ListView) rootView.findViewById(R.id.List1);
String[] test_items = {"1","2","3","4"};
ArrayAdapter<String> test_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, test_items);
listView.setAdapter(test_adapter);

关于java - ListView 导致 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23221958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com