我已經爲我的主要活動的佈局下面的代碼:如何在循環中使用ViewGroup引用?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/R0C0"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/R0C1"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/R0C2"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/R1C0"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/R1C1"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/R1C2"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/R2C0"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/R2C1"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/R2C2"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
有9個按鍵的井字棋格,每一個獨特的name.My MainActivity類別是:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends Activity {
Button g[][] = new Button[3][3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g[0][0]=(Button)findViewById(R.id.R0C0);
g[0][1]=(Button)findViewById(R.id.R0C1);
g[0][2]=(Button)findViewById(R.id.R0C2);
g[1][0]=(Button)findViewById(R.id.R1C0);
g[1][1]=(Button)findViewById(R.id.R1C1);
g[1][2]=(Button)findViewById(R.id.R1C2);
g[2][0]=(Button)findViewById(R.id.R2C0);
g[2][1]=(Button)findViewById(R.id.R2C1);
g[2][2]=(Button)findViewById(R.id.R2C2);
}
}
- 代替初始化的每個按鈕單獨,我想這樣做使用嵌套for循環的3×3陣列(即我要概括的代碼爲任何尺寸的網格)如何做 這個?
- 在LinearLayout中,eclipse警告我使用嵌套權重在性能方面表現不佳。這有什麼替代?
你有一個代碼錯誤。我想你想'g [1] [2]'而不是'g [1] [0]''。 –
不用擔心2.(替代方案是儘可能使用相對佈局)但真的不用擔心2 .. –
哦謝謝,糾正。我問了第二個問題,因爲上面的代碼不在我的模擬器中工作。應用程序在啓動時崩潰,而這種情況只發生在我使用嵌套權重時發生。 – 343GuiltySpark