如何在Android中以多行的方式逐個程式化地向佈局中新增按鈕


此示例演示瞭如何在Android中以多行的方式逐個程式化地向佈局中新增按鈕。

步驟 1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 − 將以下程式碼新增到res/layout/activity_main.xml中。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   tools:context=".MainActivity"
   android:orientation="vertical">
</LinearLayout>

步驟 3 − 將以下程式碼新增到src/MainActivity.java中

package app.com.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LinearLayout layout = new LinearLayout(this);
      layout.setOrientation(LinearLayout.VERTICAL);
      for (int i = 0; i < 3; i++) {
         LinearLayout row = new LinearLayout(this);
         row.setLayoutParams(new LinearLayout.LayoutParams
            (LinearLayout.LayoutParams.WRAP_CONTENT,
               LinearLayout.LayoutParams.WRAP_CONTENT));
         for (int j = 0; j < 4; j++) {
            Button btnTag = new Button(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams
            (LinearLayout.LayoutParams.WRAP_CONTENT,
               LinearLayout.LayoutParams.MATCH_PARENT));
            btnTag.setText("Button " + (j + 1 + (i * 4 )));
            btnTag.setId(j + 1 + (i * 4));
            row.addView(btnTag);
         }
         layout.addView(row);
      }
      setContentView(layout);
   }
}

步驟 4 - 將以下程式碼新增到androidManifest.xml中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您已將您的實際Android手機裝置連線到您的電腦。要從Android Studio執行應用程式,請開啟專案的一個活動檔案,然後點選工具欄中的執行  圖示。選擇您的手機裝置作為選項,然後檢查您的手機裝置,它將顯示您的預設螢幕 –

點選 此處 下載專案程式碼。

更新於: 2019年8月21日

2K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告