我想在應用程序啓動時隱藏所有圖像ImageButton;Android批量設置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方法,然後我得到了強制關閉,同時測試
-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" />
你不能從一個字符串獲取資源ID那樣。看到這裏:http://stackoverflow.com/a/10116885/2116951 – 2013-03-17 14:39:34