如何动态地向 Android 中添加一个按钮?


此示例演示如何在 Android 中动态添加按钮。

步骤 1 - 在 Android Studio 中创建新项目,转到 File ⇒ New Project 并填写所有必需的详细信息以创建新项目。

步骤 2 - 向 res/layout/activity_main.xml 中添加以下代码。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/relativeLayout"
   android:gravity="center"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
</RelativeLayout>

步骤 3 - 向 src/MainActivity.java 中添加以下代码

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   RelativeLayout relativeLayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      relativeLayout = findViewById(R.id.relativeLayout);
      Button button = new Button(this);
      button.setText("Dynamically created Button");
      button.setLayoutParams(new
         RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
         ViewGroup.LayoutParams.WRAP_CONTENT));
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(MainActivity.this, "This button is created dynamically",
               Toast.LENGTH_SHORT).show();
         }
      });
      if (relativeLayout != null){
         relativeLayout.addView(button);
      }
   }
}

步骤 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 中运行该应用程序,请打开项目的一个活动文件并单击工具栏中的运行 Play Icon 图标。选择您的移动设备作为选项,然后检查将显示您默认屏幕的移动设备 -

更新日期:02-Jul-2020

2K+ 查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.