【问题标题】:SetContent automaticly [duplicate]自动设置内容[重复]
【发布时间】:2019-11-18 03:33:07
【问题描述】:

我是 Android Studio 的新手,我有一个问题。 我目前正在使用这种方法来设置内容

 ImageView img1 = (ImageView)findViewBtId(R.id.Img1);
 ImageView img2 = (ImageView)findViewBtId(R.id.Img2);`

但我想排列img1,img2,img3所以我可以像这样自动设置内容

 ArrayList <ImageView> imgs = new ArrayList <ImageView>();
 imgs.add("img1");
 imgs.add("img2");
 imgs.add("img3");

 for (int i =0;int i < imgs.length();i++)
 { imgs[i] = ...;}

我可以使用这个或其他东西吗? Android Studio 不能有这样的东西吗?

【问题讨论】:

  • 您可以在循环中使用Resources#getIdentifier() 方法。它将返回数字 ID,您可以使用它来代替 R.idfindViewById()。例如,int id = getResources().getIdentifier("img" + (i + 1), "id", getPackageName());imgs.add((ImageView) findViewById(id));
  • 非常感谢,这正是我想要的。
  • 没问题。请务必选择“这解决了我的问题!”选项,以便可以将其标记为已解决。谢谢。干杯!
  • @MikeM。我无法将您的评论标记为答案(因为它是评论)所以您可以在下面放一个答案以便我标记它吗?另外我如何取消标记为重复?我试图标记您的评论并弹出:D
  • 这很酷。我只是总结了链接副本上的答案所说的内容。无需在此处的另一个答案中重复它们。这就是我们标记重复项的原因;将给定问题的解决方案保存在一个地方。你做了正确的事情。不过,谢谢。我很感激这个提议。真高兴你做到了。干杯!

标签: java android-studio


【解决方案1】:
You can assign dynemically like: 

Here is the 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="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

And the Actvity File

public class TestActivity extends Activity{

    private String[] id;
    private ImageView[] imageViews = new ImageView[2];

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

        int temp;
        id = new String[]{"img1", "img2"};

        for(int i=0; i<id.length; i++){
           temp = getResources().getIdentifier(id[i], "id", getPackageName());
           imageViews[i] = (ImageView) findViewById(temp);
        }
    }

Hope you understand and do according your need.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2014-01-07
    • 2022-06-11
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多