2011-10-02 84 views

回答

0

您可以使用一個視圖visibility屬性來控制它是否可見或不可見。這裏有一個小例子,應該做你想找的。

主要Activity

public class DynamicLayoutTestActivity extends Activity { 
    private ToggleButton toggleButton; 
    private View possiblyHiddenView; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     toggleButton = (ToggleButton) findViewById(R.id.toggleButton); 
     possiblyHiddenView = (View) findViewById(R.id.possiblyHiddenView); 

     toggleButton.setOnCheckedChangeListener(toggleButtonOnCheckedChangeListener); 
    } 

    private final CompoundButton.OnCheckedChangeListener toggleButtonOnCheckedChangeListener 
      = new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (isChecked) { 
       possiblyHiddenView.setVisibility(View.VISIBLE); 
      } else { 
       possiblyHiddenView.setVisibility(View.INVISIBLE); 
      } 
     } 
    }; 
} 

佈局文件,main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 
    <ToggleButton 
     android:id="@+id/toggleButton" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textOff="Show" 
     android:textOn="Hide" /> 
    <LinearLayout 
     android:id="@+id/possiblyHiddenView" 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:visibility="invisible" 
    > 
     <TextView 
      android:text="Stuff that could be hidden." 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" /> 
    </LinearLayout> 
</LinearLayout> 

如果你不想隱藏視圖佔用任何空間,使用可視性gone代替invisible

希望這會有所幫助!

+0

開發defintly幫助你的感謝,但是當它變得可見它仍然與其他視圖放置遊手好閒。我真正想要的是在現有組件的頂部可以看到的東西,當不需要時可以離開 – LostPuppy

+0

您的意思就像是一個對話框? –

+0

是的,但它應該有控制,我的意思是可以點擊不只是一個好的或取消按鈕 – LostPuppy

0

如果你正在爲Android 3.0+發展,看看fragments

+0

不,我爲Android 2.2 – LostPuppy

相關問題