开发者

SetVisibility not working with ImageButton

开发者 https://www.devze.com 2023-03-10 16:38 出处:网络
So I\'ve been looking around in forums for how to do this, but nothing I have found has worked.When I call setVisibility() on my image button, the button is unaffected. Below is my code that is in the

So I've been looking around in forums for how to do this, but nothing I have found has worked. When I call setVisibility() on my image button, the button is unaffected. Below is my code that is in the onCreate method, and both buttons are showing up when I run the application. However, if I were to hardcode the attribute into the xml file, the visibility does change. Any ideas why this is happening?

super.onCreate(savedInstanceState);
    setCon开发者_高级运维tentView(R.layout.main);
    btn1 = new ImageButton(this);
    btn1.setVisibility(GONE);
    btn2 = new ImageButton(this);
    btn2.setVisibility(GONE);


Change your code to :

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);

and modify your 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>


FIRST : you shoud use the method setVisibility like this :

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

SECONDE: you have created your buttons , but you didn't add them to your activity , ( the content of your activity is ( R.layout.main )

try this :

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);

EDIT :

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);
0

精彩评论

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