0

同じアクティビティ内でタブ付きのインターフェイスを作成しようとしています。これは私のmain.xmlです

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/tabhost"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabWidget android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    />
    <FrameLayout android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      <AnalogClock android:id="@+id/tab1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
      />
      <Button android:id="@+id/tab2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="A semi-random button"
      />
    </FrameLayout>
  </LinearLayout>
</TabHost>

ダミー.xml:

<?xml version="1.0" encoding="utf-8"?>

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:orientation="vertical" >

      <RatingBar
          android:id="@+id/ratingBar1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

  </LinearLayout>

と私の活動:

public class LActivity extends Activity {


 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);


     TabHost tabs=(TabHost)findViewById(R.id.tabhost);
     tabs.setup();

   tabs.addTab(tabs.newTabSpec("tag1").setIndicator("1").setContent(R.id.tab1));
   tabs.addTab(tabs.newTabSpec("tag2").setIndicator("2").setContent(R.id.tab2));

上記のコードは機能しますが、またはに変更R.id.tab2すると、nullpointerexceptionがスローされます。R.layout.dummyR.id.ratingBar1

tabにdummy.xmlを表示するつもりです。

4

1 に答える 1

6

動作する理由とR.id.tab2動作R.layout.dummyしない理由は、で設定されたレイアウトで定義されているコンテンツビューR.id.tab2の一部であるためです。ActivitysetContentView

view-idが期待される場所でlayout-idを使用することはできません。そのため、機能しません。また、コンテンツの一部ではないので使用する場合、それが機能することを期待することはできません。アクティビティは、そのビューを取得する場所をどのように知るのでしょうか。idを使用していくつかの異なるレイアウトを持つことができることを忘れないでください。R.layout.dummyR.id.ratingBar1ActivityratingBar1

必要なのは、ダミーレイアウトを内に配置すること@android:id/tabcontentです。<include>これは、要素だけで実行できます。それ以外の場合は、自分でレイアウトを膨らませ、その結果Viewをの引数として使用する必要がありますsetContent

于 2012-05-30T17:53:32.420 に答える