SetVisibility无法使用ImageButton

时间:2011-06-07 00:12:38

标签: android visibility imagebutton

因此,我一直在论坛中寻找如何做到这一点,但我发现没有任何效果。当我在图像按钮上调用setVisibility()时,该按钮不受影响。下面是我在onCreate方法中的代码,当我运行应用程序时,这两个按钮都会显示出来。但是,如果我要将属性硬编码到xml文件中,则可见性会发生变化。任何想法为什么会发生这种情况?

super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn1 = new ImageButton(this);
    btn1.setVisibility(GONE);
    btn2 = new ImageButton(this);
    btn2.setVisibility(GONE);

2 个答案:

答案 0 :(得分:3)

将您的代码更改为:

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (ImageButton)findViewById(R.id.btn1);
btn1.setVisibility(View.GONE);
btn2 = (ImageButton)findViewById(R.id.btn2);
btn2.setVisibility(View.GONE);

并修改main.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:gravity="center_horizontal"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:orientation="vertical"
                  >
        <Button android:id="@+id/btn1" android:layout_width="100dip" 
            android:layout_height="40dip" android:text="btn1"/>       
        <Button android:id="@+id/btn2" android:layout_width="100dip" 
            android:layout_height="40dip" android:text="btn2"/>

    </LinearLayout>

答案 1 :(得分:0)

第一:你应该像这样使用setVisibility方法:

btn1.setVisibility(VIEW.GONE),// not setVisibility(GONE);

SECONDE:  您已创建按钮,但you didn't add them to your activity,(您的活动内容为(R.layout.main

试试这个:

super.onCreate(savedInstanceState);

    btn1 = new ImageButton(this);
    setContentView(btn1);
    btn1.setVisibility(VIEW.GONE);
    try{
          Thread.sleep(3000);//pause 3 secondes 
    }catch(Exception e){}
    btn1.setVisibility(View.VISIBLE);

编辑:

super.onCreate(savedInstanceState);

    LinearLayout layout = new LinearLayout(this);
    ImageButton btn1 = new ImageButton(this);
    ImageButton btn2 = new ImageButton(this);
    layout.addView(btn1);
    layout.addView(btn2);
    setContentView(layout);
    btn1.setVisibility(VIEW.GONE);
    btn2.setVisibility(VIEW.VISIBLE);
    try{
          Thread.sleep(3000);//pause 3 secondes 
    }catch(Exception e){}
    btn1.setVisibility(View.VISIBLE);
    btn2.setVisibility(VIEW.GONE);