2
我正在爲Android編寫一些代碼,問題在於,當我調用findViewById時它返回null,我不明白爲什麼!我從昨天開始一直在浪費我的大腦,但我無法弄清楚解決方案。目標是將佈局設置爲listView的標題。這裏是我的代碼,分別爲我的頭和我的網頁:Android,findViewById返回null
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/header"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<TextView
android:text="@string/bydistance"
android:layout_gravity="left"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textSize="13dp"
android:gravity="center_horizontal"/>
<TextView
android:text="@string/byactivity"
android:layout_gravity="right"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textSize="13dp"
android:gravity="center_horizontal"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"
>
<ListView
android:id="@+id/parkList"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:divider="@android:color/transparent"
android:dividerHeight="5.0dp">
</ListView>
</LinearLayout>
在這裏,我的代碼,我叫addheaderView:
public class NearMeFragment extends Fragment implements View.OnClickListener{
private FragmentManager fragmentManager;
@Override
public void onCreate(Bundle savedBundle){
super.onCreate(savedBundle);
}
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedBundle) {
View v = inflater.inflate(R.layout.park_list, container, false);
//TODO remove
make_test(v, container);
return v;
}
public void openTest(View view){
new LiveComment().show(getChildFragmentManager(), "dialog");
}
public void onClick(View view){
if (fragmentManager == null)
fragmentManager = getChildFragmentManager();
//if (view.getId() == R.id.test){
fragmentManager.beginTransaction().add(new LiveComment(), "livecomment").commit();
}
private void make_test(View v, ViewGroup container) {
ListView listView = (ListView) v.findViewById(R.id.parkList);
Park[] list = new Park[3];
list[0] = new Park("parco a", "acquasparta", false, false, 1, 2, 3);
list[1]=new Park("parco b", "perugia", false, false, 1, 2, 3);
list[2]=new Park("parco b", "perugia", false, false, 1, 2, 3);
ParkListAdapter adapter = new ParkListAdapter(v.getContext(), R.layout.small_park_container,list);
LinearLayout header = (LinearLayout) container.findViewById(R.id.header);
listView.addHeaderView(header);
listView.setAdapter(adapter);
}
}
誤差以
listView.addHeaderView(header)
我已經嘗試過了。但是我已經重試過了,它給了我同樣的錯誤 – litiales
在你發佈的佈局裏面你爲什麼要把<?xml version =「1.0」encoding =「utf-8」?>兩次?那兩種不同的佈局? – Blackbelt
是的!我已經將標題定義爲分隔佈局。我不應該這樣做嗎? – litiales