将 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/