如何在 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" android:id="@+id/parent" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:gravity="center" android:orientation="vertical"> </LinearLayout>
在上面的程式碼中,我們採用了一個空佈局。在此佈局中,我們將有動態文字檢視。
package com.example.andy.myapplication;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parent);
TextView textView = new TextView(MainActivity.this);
textView.setText("Child Row");
parentLayout.addView(textView);
}
}在上面的程式碼中,我們為父檢視動態建立了一個文字檢視。
讓我們嘗試執行您的應用程式。我假設您已將實際的 Android 移動裝置連線到計算機。要從 android studio 執行該應用程式,請開啟專案的其中一個活動檔案,然後單擊工具欄上的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 −

在上面的結果中,我們已經添加了一個動態文字檢視。
點選 此處 下載專案程式碼
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP