繁体   English   中英

如何从 Java inflate 定位布局 ID

[英]How can I target layout id from Java inflate

我是 Android 编程的新手......我想以编程方式将布局添加到ScrollView ,所以我使用下面的代码

for(int i = 0; i < 10; i++){
    LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.my_layout, null);
    ImageView imgView = (ImageView) getLayoutInflater().inflate(R.layout.img_view, null);
    //set ImageView source
    TextView txtView = (TextView) getLayoutInflater().inflate(R.layout.txt_view, null);
    //set TextView text
    myLayout.addView(imgView);
    myLayout.addView(txtView);
    scrllView.addView(myLayout);
}

上面的代码工作正常。 但是我想知道是否有更短更简单的方法来做到这一点,因为我的代码会很庞大,而且我必须为我要添加的每个视图创建一个布局 XML 文件

也许我在想,而不是在我的布局文件夹中创建多个 XML 文件,我可以只有一个 XML 文件,将LinearLayout作为父级, ImageViewTextView作为子级,所以my_layout.xml看起来像这样

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

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/img"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt"/>

</LinearLayout>

然后我可以在我的 Java 代码中膨胀my_layout.xml文件,使用它们的IDs添加目标ImageViewTextView

LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.my_layout, null);
ImageView imgView = //find the child of myLayout (ImageView) with ID of img
//set ImageView source
TextView txtView = //find the child of myLayout (TextView) with ID of txt
//set TextView text

我想知道是否有可能实现这一目标。

好吧...我终于得到了我要找的东西。 下面的代码工作得很好

LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.my_layout, null);
ImageView imgView = myLayout.findViewById(R.id.img);
//set ImageView source
TextView txtView = myLayout.findViewById(R.id.txt);
//set TextView text

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM