android - 通过 addContentView 添加以 XML 定义的 View

标签 android android-view

我正在使用 addContentView 将 subview 添加到我的主视图,如下所示:

    TableLayout.LayoutParams tlp = new TableLayout.LayoutParams(
            TableLayout.LayoutParams.WRAP_CONTENT,
            TableLayout.LayoutParams.WRAP_CONTENT);

    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_NAME);
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    addContentView(textView,tlp);

我可以在 xml 文件中定义 View ,然后通过 addContentView 添加它,而不是像上面那样以编程方式定义 View 吗?

谢谢!

最佳答案

can I define the view in an xml file and then add it via addContentView?

是的,首先使用 LayoutInflater 膨胀 xml 文件它返回一个 View。设置布局 LayoutParams

后将 View 传递给 addContentView
LayoutInflater inflater = getLayoutInflater();
View view;
view = inflater.inflate(R.layout.xml_file_name, null);
//.. add LayoutParams to view

// call addContentView
addContentView(view,tlp);

关于android - 通过 addContentView 添加以 XML 定义的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41512336/

相关文章:

android - RecoverySystem.installPackage java.lang.NullPointerException

android - 如何使用aidl将ITelephony.aidl转换为ITelephony.java

android - 没有适配器连接到 viewpager2

android - 像 Android 4.4 一样创建蓝色 "tutorial"对话框

android - 在 strings.xml 中使用特殊字符在 WebView 中加载

android - 如何用圆角制作 View ?

Android交叉编译C,无配置文件

android - 如何自动滚动 MPAndroidChart 折线图?

android - 按顺序将动画应用到多个 View

android - 如何将我的布局拆分为 3 个不同的滑动 View