2011-12-14 115 views
0

我有一個問題按鈕的可見性。我有2個來自標題欄的按鈕。其中一個編輯,其中一個完成。首先,我想看到只是編輯按鈕,當我點擊編輯按鈕,編輯按鈕的可見性將是錯誤的,並完成按鈕可見性真實。以編程方式從標題欄更改可見性按鈕?

我從XML獲得他們的ID,當我點擊其中一個我想改變可見性,但edit.setVisibility();它不工作。怎麼了?我可以看到編輯按鈕。我想以編程方式更改按鈕的可見性。

任何人都可以有任何想法嗎?

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

    final boolean customTitle = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 

    setContentView(R.layout.main); 

    edit=(Button)findViewById(R.id.edit); 
    done=(Button)findViewById(R.id.done); 

    edit.setVisibility(View.INVISIBLE); 
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.main); 

    if (customTitle) { 
     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.main); 
    } 

的main.xml:

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

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

    <Button android:id="@+id/edit" 
      android:layout_width="57px" 
      android:layout_height="wrap_content" 
      android:text="edit"/> 

    <Button android:id="@+id/done" 
      android:layout_width="57px" 
      android:layout_height="wrap_content" 
      android:text="done"/> 

</LinearLayout> 
+1

請對這種行爲使用操作欄。操作欄在Android 3.0+上是原生的,並且有多種庫用於在較早版本的Android上提供操作欄(例如,ActionBarSherlock)。 – CommonsWare 2011-12-14 14:00:27

回答

0

首先,你錯過了android:在你的LinearLayout定向參數。

第二,如果你想與編輯之間的變化做,你可以這樣做:

edit.setVisibility(View.GONE); 
done.setVisibiluty(View.VISIBLE); 

和對面來改變重新編輯按鈕。隨着View.INVISIBLE按鈕不會顯示,但仍使用它的位置。

0

問題是setFeatureInt只是設置標題的資源ID,這將導致佈局資源的新的膨脹,它將被放置在稱爲id/title_container的系統FrameLayout中。這可以使用eclipse中的Hierarchy Viewer進行檢查。

本質上,你最終得到兩個主佈局的實例。一組作爲內容視圖(標題下方),另一組作爲標題。當您致電findViewById時,它只會在內容視圖中查看與該ID匹配的任何視圖。這意味着您檢索的editdone按鈕是內容視圖中的按鈕。

如果您要訪問的標題區域中的按鈕,你可以使用

View v = getWindow().getDecorView(); 
    edit=(Button)v.findViewById(R.id.edit); 
    done=(Button)v.findViewById(R.id.done); 
    edit.setVisibility(View.INVISIBLE); 

這將通過這個窗口,而不僅僅是內容畫面的整體視圖結構進行搜索,從而解決您的問題。

相關問題