Android批量设置ImageButton可见性

时间:2013-03-17 14:32:04

标签: android view visibility imagebutton batch-processing

我想在应用启动时隐藏所有图像ImageButton;

我该怎么归档?这是代码:

ImageButton imgBtn[];

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
                hideBtn();
}

private void hideBtn(){
        for (int i = 0; i < 3; i++) {
            imgBtn[i] = (ImageButton) findViewById("R.id.myBTN"+[i]);
            imgBtn[i].setVisibility(View.GONE);
        }
}

更新 我改变了hideBtn方法,然后在测试

时得到了Force Close
 -159   private void hideBtn(){
 -160       for (int i = 0; i < 3; i++) {
 -161           int id = getResources().getIdentifier("myBTN"+i,"id", "com.my.app");
 -162           imgBtn[i] = (ImageButton)findViewById(id);
 -163           imgBtn[i].setVisibility(View.GONE);
 -164       }
 -165   }

崩溃日志报告:

03-18 16:46:05.125: E/AndroidRuntime(19463):    at dalvik.system.NativeStart.main(Native Method)
03-18 16:46:05.125: E/AndroidRuntime(19463): Caused by: java.lang.NullPointerException
03-18 16:46:05.125: E/AndroidRuntime(19463):    at com.my.app.Main.hideBtn(Main.java:162)
03-18 16:46:05.125: E/AndroidRuntime(19463):    at com.my.app.Main.onCreate(Main.java:61)
03-18 16:46:05.125: E/AndroidRuntime(19463):    at android.app.Activity.performCreate(Activity.java:5108)
03-18 16:46:05.125: E/AndroidRuntime(19463):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-18 16:46:05.125: E/AndroidRuntime(19463):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
03-18 16:46:05.125: E/AndroidRuntime(19463):    ... 11 more

更新: 这是xml代码:

<ImageButton
        android:id="@+id/myBTN1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/button" />

<ImageButton
        android:id="@+id/myBTN2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myBTN1"
        android:layout_below="@+id/myBTN1"
        android:layout_marginTop="12dp"
        android:background="@drawable/button" />

<ImageButton
        android:id="@+id/myBTN3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myBTN2"
        android:layout_below="@+id/myBTN2"
        android:layout_marginTop="12dp"
        android:background="@drawable/button" />

1 个答案:

答案 0 :(得分:1)

findViewById需要类型为int的参数,但是您传递的是字符串类型。 您需要先获取资源ID。

你可以使用资源类的getIdentifier方法来获取id,检查这个getIdentifier

喜欢这个

int id=getResources().getIdentifier("myBTN"+[i], "id", "com.mypackage.myapp");

然后

imgBtn[i] = (ImageButton) findViewById(id);