2012-05-03 64 views
2

親愛的我使用下面的代碼來創建自定義標題與圖像view.But它顯示圖像視圖的空指針異常。如何解決這個問題?自定義標題欄與圖像視圖爲TabActivity

public class MyCustomTab2Activity extends TabActivity { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
        //Tab Content 
     setContentView(R.layout.my_tab_home);  
     ImageView imag = (ImageView) findViewById(R.id.iv_logout);   
     imag.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 

     } 
     }); 
        //custom title bar content 
     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.logintitle); 

     ...... 


     ........... 


    } 

} 
+0

是的。我需要做.. –

+0

我試過你的代碼。我也收到了空指針異常。試試我更新的答案。是否有用? – Praveenkumar

回答

0

只要把下面的代碼在你的TabHost主要活動 -

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 

    setContentView(R.layout.main); 

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); 

    ImageView image = (ImageView)findViewById(R.id.header); 

    image.setOnTouchListener(new OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      // TODO Auto-generated method stub 

      Toast.makeText(CustomWindowTitle.this, "This is sample", Toast.LENGTH_SHORT).show(); 

      return false; 
     } 
    }); 
} 

Window_title.xml

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:layout_height="35dip" 
android:gravity="center_vertical" 
android:paddingLeft="5dip" 
android:background="#323331"> 

<ImageView 
    android:id="@+id/header" 
    android:src="@drawable/header" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 

</LinearLayout> 

希望這能對你有所幫助。見下面我的輸出 -

CustomWindowTitle

更新

我知道了。你宣稱圖像的OnclickListener後您的自定義標題請像下面在你的代碼的變化 -

public class MyCustomTab2Activity extends TabActivity { 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
       //Tab Content 
    setContentView(R.layout.my_tab_home);  

    //custom title bar content 
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.logintitle); 

    ImageView imag = (ImageView) findViewById(R.id.iv_logout);   
    imag.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 

    } 
    }); 

    ...... 


    ........... 


} 

} 

希望這有助於你。

0

ImageView並非真正用於這種方式,您可以嘗試兩件事。設置以下標誌ImageView,imag.setFocusable=(true),看看是否有效,或者改爲嘗試使用ImageButtonButton,將background屬性設置爲圖像,因爲它旨在用於這種方式。