android - 如何在 java 代码中管理 UI?

标签 android android-activity

将 contentView 设置为布局后,如何通过 java 管理 UI?另外,如果我开始一项新 Activity ,是否会重置 contentView?

最佳答案

ContentView 只会在一个 Activity 中。

假设您在扩展 Activity 的地方,在设置内容 View 后,您所要做的就是访问您的 View 。假设您的布局中有一个按钮:

Button homeButton = (Button) findViewById(R.id.homeButton);
homeButton.setText(); homeButton.setOnClickListener() etc

如果您处于对话中,或需要在特定情况下访问某些 View ,或者您处于 Intent 中并且需要访问主要 Activity 布局中的内容:

Button secondButton = (Button) getActivity().findViewById(R.id.secondButton);
//other methods on the button

编辑--

好的图片,你只需在布局中添加一个 ImageView 即可:

<ImageView android:id="@+id/logoImageView"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:src="@drawable/logo" android:contentDescription="@string/app_name" 
        android:layout_gravity="center_horizontal"/>

您无需专门对代码执行任何操作,它应该直接显示出来。

按钮和其他 View 也可以通过 XML 添加。您也可以通过编程方式添加内容,但并不常见。

如果我没记错的话,用 Java 创建按钮的构造函数不在您的 XML 文件中,它将是 Button aNewButton = new Button(getApplicationContext()); aNewButton.setText("随便");

关于android - 如何在 java 代码中管理 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889590/

相关文章:

android - 在 Android 中使用 HttpsURLConnection 的 SSLHandshakeException

java - `MediaStore.MediaColumns.DATA` 已弃用,我应该使用哪一列作为替代

android - 自定义 support.v7.widget.Toolbar 未在设备上显示

java - Android 数学测验(线程操作)

android - Espresso 测试 : Accessing Variables

android - 如何将我的 Android 应用程序添加到共享对话框?

android - 为本地镜像创建适用于 Android 的照片库应用程序

java - Android - 需要 Activity 但不想要 Activity ?

android - 嵌套的 startActivityForResult()

android - 在我的案例中如何控制/修改 Activity 堆栈