以编程方式将视图添加到 LinearLayout 但它们不显示

2024-01-26

我正在尝试填充一个LinearLayout inside simple_pdf_example.xml与 10printed_order_element2.xml这样我就可以生成一个 PDFListView(这实际上是一个LinearLayout).

问题是当我这样做时linearLayoutView.addView(v)10次​​了,没看到v在 - 的里面LinearLayout。我只是看到我在 xml 中添加的原始项目只是为了看看是否LinearLayout正在渲染。

SimplePDFSaver.java:

package com.mypackage.example;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import java.io.File;
import java.io.FileOutputStream;


public class SimplePDFSaver extends AppCompatActivity {
    private static final String TAG = "SimplePDFSaver";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_pdfsaver);
        generatePDF();
    }

    public void generatePDF() {
        LayoutInflater inflater = getLayoutInflater();
        View pdfLayout = inflater.inflate(R.layout.simple_pdf_example,
            findViewById(android.R.id.content),
            false);


        int sizeSpec = View.MeasureSpec.makeMeasureSpec(2480, View.MeasureSpec.EXACTLY);
        int sizeSpec2 = View.MeasureSpec.makeMeasureSpec(3508, View.MeasureSpec.EXACTLY);
        pdfLayout.measure(sizeSpec, sizeSpec2);

        int width = pdfLayout.getMeasuredWidth();
        int height = pdfLayout.getMeasuredHeight();
        pdfLayout.layout(0, 0, width, height);

        LinearLayout linearLayoutView = pdfLayout.findViewById(R.id.linearLayoutView);

        for (int i=0; i<10; i++) {
            View v = getLayoutInflater().inflate(R.layout.printed_order_element2, null);
            linearLayoutView.addView(v);
        }

        Runnable r = new Runnable() {
            @Override
            public void run() {

                PdfDocument document = new PdfDocument();
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
                PdfDocument.Page page = document.startPage(pageInfo);

                pdfLayout.draw(page.getCanvas());
                document.finishPage(page);

                FileOutputStream outStream;
                File file = new File(getExternalFilesDir(null), "file.pdf");
                try {
                    outStream = new FileOutputStream(file);
                    document.writeTo(outStream);
                    document.close();
                    outStream.flush();
                    outStream.getFD().sync();
                    outStream.close();

                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    Uri uri = FileProvider.getUriForFile(SimplePDFSaver.this, BuildConfig.APPLICATION_ID + ".provider", file);
                    intent.setDataAndType(uri, "application/pdf");
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, e.toString());
                }
            }
        };
        new Thread(r).start();
    }
}

simple_pdf_example.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayoutView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView10">


        <TextView
            android:id="@+id/textView13"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Just to see if linearLayoutView rendered" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="There should be a list of items below:"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

打印的_order_element2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

这就是我得到的:


我认为问题出在这一段代码上:

public void generatePDF() {
    LayoutInflater inflater = getLayoutInflater();
    View pdfLayout = inflater.inflate(R.layout.simple_pdf_example,
            findViewById(android.R.id.content),
            false);

所有其余的代码都使用这个膨胀的pdfLayout view:

LinearLayout linearLayoutView = pdfLayout.findViewById(R.id.linearLayoutView);

for (int i=0; i<10; i++) {
    View v = getLayoutInflater().inflate(R.layout.printed_order_element2, null);
    linearLayoutView.addView(v);
}
pdfLayout.draw(page.getCanvas());

问题是你的pdfLayout视图永远不会显示在屏幕上。你的setContentView()打电话进来onCreate()膨胀不同的布局,并且膨胀pdfLayout从来不依附于任何视图!

你打电话时inflate(int, View, boolean)并通过false作为第三个参数,您告诉系统处理第二个参数(View) 作为父级only为了解析LayoutParams在膨胀布局的根部。膨胀的布局不会添加到父级!你必须手动调用parent.addView()与膨胀的视图。


如何修复它?很难准确地说,因为我有几个问题。但也许只要提出问题就会揭示答案。

看到很奇怪both打电话给setContentView()并致电inflate()传入的android.R.id.content作为家长。你可以打电话吗setContentView(R.layout.simple_pdf_example)在你的onCreate(),并避免第二个inflate()一起打电话吗?

如果是这样,那么您将替换所有调用pdfLayout.findViewById()与直接findViewById()调用(因为之前的pdfLayout现在只是您的活动的主要内容)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式将视图添加到 LinearLayout 但它们不显示 的相关文章

随机推荐

  • 如何将图标和文本段落放在一行中?

    我想将我的字体很棒的图标和文本段落放到一行中 我该如何修复此代码 div class date style display inline block i class fa fa user o i p style display inline
  • Maven 3 - 值得吗? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 是否有可能获得一个 .xib 窗口到选项卡式故事板

    我没有很长时间编写代码 Xcode 所以我有点垃圾 基本上我已经创建了一个 xib 并希望它出现在故事 板中 但我真的不知道从哪里开始 因为我有一个 xib 窗口具有UITableView and UIPickerView其中所有代码在 x
  • 将带标签的 pandas DF 写入 influxdb

    我有这个 3526 rows x 5 columns DF 其中col0是时间 col1 col3是标签和col4是我的价值 0 1 2 3 4 0 2017 09 29 22 41 51 10 2 95 5 C1195 LF470 SAR
  • JavaScript通过点击改变当前元素的颜色

    我有一个关于仅更改当前元素的颜色的问题 所以我想通过每次点击来更改当前元素的背景颜色 我的问题是 我无法重置前一个元素的背景颜色 例如 我这里有两种背景颜色 黄色 浅蓝色 如果我单击 旧 div 和 新 div 则两个 div 的背景颜色变
  • 将代码字符串转换为 hive 中的 desc

    这里我们有一个连字符的字符串 例如0 1 3 并且长度不固定 hive 中还有一个 DETAIL 表来解释每个代码的含义 DETAIL code desc 0 AAA 1 BBB 2 CCC 3 DDD 现在我们需要一个 hive 查询来将
  • 如何从 DIV 重定向并绕过子锚点 href

    请我需要您的帮助来完成下面的代码 我想向整个 DIV 添加 onclick 事件以重定向到 url 但我无法绕过 DIV 内子锚点中包含的 href 即 目标是点击图像或文本上的任意位置重定向到 google com div div a h
  • 未找到带有 SQLalchemy 数据库的 PostgreSQL

    我使用以下代码使用 sqlalchemy 创建 postgresql 数据库 engine create engine postgresql psycopg2 postgres localhost testData Base metadat
  • 对于自动返回类型,使用哪种更好: decltype 或 std::common_type<>::type (如果可能)?

    作为对我的回答最后一个问题 https stackoverflow com questions 11052842 error with using decltype in c11 creating opaque error message
  • 爱尔兰 Eircode 验证

    我想知道是否有验证爱尔兰 Eircode 格式的最佳实践 到目前为止 我在 JavaScript 中使用 REGEX 的最佳尝试是基于第 11 页上的官方规范here https www eircode ie docs default so
  • Apache Poi excel 删除空白行

    我有一个 3000 行的 Excel 文件 我删除了2000 使用ms excel应用程序 但是当我从代码中调用sheet getLastRowNum 时 它给了我3000 而不是1000 我如何删除空白行 我尝试了来自的代码here ht
  • IIS 7 Cors Ajax Soap 请求

    我遇到了一个无法解决的问题 我有一些 js jquery POST Soap 通过 PHP 请求代码在 Apache 上工作 启用了 Cors 来调用 HTTPS 并且工作正常 我已经迁移到 IIS7 设置响应标头 Access Contr
  • 在 PowerShell 中使用另一个扩展 JSON

    是否有一些简单的方法可以将一个 JSON 文件扩展为另一个文件 并使用 PowerShell 将输出保存到另一个文件 目前我正在尝试编写一个允许我做到这一点的循环函数 但也许有一个更简单的解决方案 迭代转换为 JSON 的属性PSCusto
  • 角度 Ui 树递增是重复的

    我的笨蛋 https plnkr co edit dlG6bJcBP8jaxhVEZ4wq p preview 在 My plunker 中 如果我添加一些子记录 那么如果我删除其中一个子记录 那么如果我添加行 则行会重复 scope ne
  • 将数据从 Android 发送到 PHP 服务器

    我在 android 中有一个应用程序 我想通过 url like mydata php lat 76867 long 87979 我有 php 代码 如果点击此 url 则将数据保存在数据库中 我所不知道的是如何通过我的android手机
  • 在 ASP.NET 中使用线程是否存在任何不明显的危险?

    这是一个兄弟姐妹的问题这个程序员的问题 https softwareengineering stackexchange com questions 13711 servicing background tasks on a large si
  • 设置elasticsearch php客户端的connect_timeout

    我想在我的elasticsearch php 客户端到我的elasticsearch 服务器之间配置一个小的超时 我尝试将一些参数传递给 guzzle 客户端 但似乎这不起作用 这是代码 params array params hosts
  • 如何在appdelegate中关闭viewcontroller?

    我为这样的暂停视图创建launchScreen func applicationWillResignActive application UIApplication let storyboard UIStoryboard name Main
  • Thymeleaf 复选框未传递值

    两个问题 我有用户和注释课程 用户可以有很多笔记 如何通过 Thymeleaf 显示属于用户的每个笔记 id th text u notes id 不起作用 我有一个表格 见图 其中每个用户都有布尔 isUserChecked 值的复选框
  • 以编程方式将视图添加到 LinearLayout 但它们不显示

    我正在尝试填充一个LinearLayout inside simple pdf example xml与 10printed order element2 xml这样我就可以生成一个 PDFListView 这实际上是一个LinearLay