开发者

make a frame with components visible only when needed in android

Well what i wanted 开发者_JAVA技巧to do was create an initial layout which will have a toggle button and on clicking the toggle but it should make a frame visible which will have a few buttons or textviews.

Does anybody know how to do this in Android 2.2??


You can use the visibility attribute on a view to control whether it is visible or not. Here's a small example that should do what you're looking for.

The main 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);
            }
        }
    };
}

The layout file, 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>

If you don't want the hidden view to take up any space, use visibility gone instead of invisible.

Hope this helps!


If you're developing for Android 3.0+, look into fragments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜