java 克隆 textview 以将其附加到 ViewGroup

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3900044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:54:11  来源:igfitidea点击:

Clone textview to append it to a ViewGroup

javaandroidviewstextview

提问by Arkaitz Jimenez

I have a ViewGroup defined in XML with a view inside, at onCreate time I'd like to have a variable of those.
I don't want to go through the hassle of using a listview+adapter cause its clearly overkill as I know the list won't change since onCreate()
This is more or less the code I'd like to have.

我有一个用 XML 定义的 ViewGroup,里面有一个视图,在 onCreate 时间我想要一个变量。
我不想经历使用 listview+adapter 的麻烦,因为我知道列表不会改变,因为 onCreate()
这或多或少是我想要的代码。

TextView mytextview = myViewGroup.findViewById(R.id.mytext);

for(String test : strings){
  mytextview = mytextview.clone();
  mytextview.setText(test);
  myViewGroup.addView(mytextview);
}

But it is not working.

但它不起作用。

回答by Mathias Conradt

Maybe use an inflater, and put the textview in an external layout file:

也许使用充气器,并将 textview 放在外部布局文件中:

View v = LayoutInflater.from(this).inflate(R.layout.textview_include, null);
viewGroup.addView(v);

回答by Khaled Annajar

Using code of Mathias Lin and using the hint from javahead76:

使用 Mathias Lin 的代码并使用来自 javahead76 的提示:

LinearLayout x = (LinearLayout) findViewById(R.id.container); 

    for (int i = 0; i < 5; i++) {
        View c = LayoutInflater.from(this).inflate(R.layout.singlerow, x);  
        TextView t = ((TextView)findViewById(R.id.textView1));
        t.setId(i+10000);
        t.setText("text"+i);            
    }
    TextView b = (TextView) findViewById(10003);
    b.setText("10003");

回答by javahead76

If you do this, you will most likely get the exact same id for every view created this way. This means doing things like ((TextView)v).setText("some text"); will be called on every TextView previously inflated from the same layout. You can still do it this way, but you should call setId() and have some reasonable method for ensuring you do not get the same id twice in a row - incrementation or universal time, etc.

如果您这样做,您很可能会为以这种方式创建的每个视图获得完全相同的 ID。这意味着做这样的事情 ((TextView)v).setText("some text"); 将在之前从同一布局膨胀的每个 TextView 上调用。你仍然可以这样做,但你应该调用 setId() 并有一些合理的方法来确保你不会连续两次获得相同的 id - 增量或通用时间等。

Also, I think Android reserves a certain range of id's for dynamically created id's. You might avoid ID's in this range; but honestly, I don't know the id system works so I could be wrong on this point.

另外,我认为 Android 为动态创建的 id 保留了一定范围的 id。您可能会避免在此范围内使用 ID;但老实说,我不知道 id 系统有效,所以在这一点上我可能是错的。