我找到了两个 SO 线程,告诉我们如何将 title 居中和 message在一个 AlertDialog
对象中,并通过编写一个我希望能够调用以居中任何 AlertDialog
的方法来伪造我的方式。它在手机和平板电脑上运行良好,甚至可以显示多行消息,包括和不包括 '\n'
。
public void showCenteredInfoDialog(TextView _title, TextView _message) {
_title.setGravity(Gravity.CENTER);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("OK", null);
builder.setCustomTitle(_title);
builder.setMessage(_message.getText());
AlertDialog dialog = builder.show();
TextView messageView = (TextView)
dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);
}
我做了相当多的定制——也就是说,我对我发现和做了什么有一些线索——但有一句话让我想知道:
TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
什么是 android.R.id.message?
Here是我能找到的关于它的所有文档:
android.R.id
public static final int message = 16908299
在哪里可以找到有关 Android.R.id
对象(以及更多)的更多文档?这似乎是一个可能的金矿。
最佳答案
在 Android 中,布局中包含的 View 通常(但不总是)有一个 ID。这个 id 的目的是能够识别特定的 View ,例如:
Button button = (Button)layout.findViewById(R.id.button1);
button.setOnClickListener(...);
当您创建一个布局 XML 文件时,您通常会为您的 View 创建新的 ID,语法是:
<Button
android:id="@+id/button1"
...
这将在您的项目 R 文件 (R.id.button1
) 中创建一个整数值。
android.R.id
包含在 Android 框架中定义或必须以某种方式引用的 View 的 ID。
在您的示例中,AlertDialog.Builder
创建了一个带有固定 id android.R.id.message
的 TextView。这样,您就可以获取 show()
返回的 View 层次结构,并在其中找到 TextView。
您可以查看预定义 ID in the documentation 的完整列表,但是此列表本身的信息量不大。这些 ID 通常在使用它们的每个特定功能的文档中提及。
作为其他用例的示例(使用预定义的 android id 标记您自己的 View ),当使用 ListFragment
时,如果您提供自定义布局,则必须包含一个 id 为 R.id.list
的 ListView .这是因为 ListFragment
类会检查膨胀的布局以查找此小部件。查看 documentation :
ListFragment has a default layout that consists of a single list view. However, if you desire, you can customize the fragment layout by returning your own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle). To do this, your view hierarchy must contain a ListView object with the id "@android:id/list" (or list if it's in code)
Optionally, your view hierarchy can contain another view object of any type to display when the list view is empty. This "empty list" notifier must have an id "android:empty".
关于android - 什么是 android.R.id.message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24748567/