android访问包含在另一个布局中

时间:2013-11-10 14:38:19

标签: android

您好我正在尝试使用我已包含在布局中的标题视图创建列表视图。问题是我从标题中的textview获取空指针异常。我认为这是因为它无法找到它所以我的问题是如何访问包含在另一个布局中的元素?

继承我的活动布局

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

   <include layout="@layout/listview_header" 
      android:id="@+id/listheader" />

   <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
   />

</TableLayout>

继承我的收录清单view_header

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" 
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:padding="10dp"
    android:id="@+id/header"
    >


     <TextView android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:textSize="14dp"
        android:textColor="#ffffff"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" 
        android:shadowColor="@color/Black"
        android:shadowDx="1"
        android:shadowDy="1"
        android:shadowRadius="0.01"/>

</LinearLayout>

并且继承我的java

      setContentView(R.layout.lo_listview_with_header);
      gilSans = Typeface.createFromAsset(getAssets(), "fonts/gillsans.ttf");
      listView = (ListView) findViewById(android.R.id.list);
      header = getLayoutInflater().inflate(R.layout.listview_header, null);
      title = (TextView) header.findViewById(android.R.id.title);


      Bundle intent = getIntent().getExtras();
      int position = intent.getInt("position") + 1;
      String backgroundColor = intent.getString("bg_color");
      String titleText = intent.getString("title");


      TextView tvTitle = (TextView)  header.findViewById(R.id.title);
      header.setBackgroundColor(Color.parseColor(backgroundColor));
      title.setText(titleText);

  }

1 个答案:

答案 0 :(得分:1)

我看到两个问题。

首先,当你真正想要做的是获取已经包含在活动布局中的listview_header时,你正在给新的listview_header充气。

你在做什么:

header = getLayoutInflater().inflate(R.layout.listview_header, null);

你想做什么:

header = findViewById(R.id.listheader);

其次,你使用错误的ID来找到你的头衔;你想要R.id.title,而不是Android.R.id.title。在XML中使用@ + id /时,Java将使用R.id;当您在XML中使用@android:id /时,您的Java将使用android.R.id。所以:

  • @ + id / id_name =&gt; findViewById(R.id.id_name);
  • @android:id / id_name =&gt; findViewById(android.R.id.id_name);

那你现在在做什么:

title = (TextView) header.findViewById(android.R.id.title);

你想做什么:

title = (TextView) header.findViewById(R.id.title);

希望这有帮助。