java - 自动设置内容

标签 java android-studio

我是 Android Studio 的新手,我有一个问题。 我目前正在使用此方法来 SetContent

 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 不能有这样的东西吗?

最佳答案

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.

关于java - 自动设置内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907650/

相关文章:

java - Android ListView 根据页脚大小将内容包装到一定大小

java - 更改应用程序:layout_constraintHorizontal_bias ="" in the ConstraintLayout

java - 打包的 C 结构和函数可以移植到 java 吗?

安卓工作室 : Application themes aren't correctly applied

gradle - 打开项目时解决和防止 "The project is using an unsupported version of Gradle"

java - 为什么有些服务器同时运行 Tomcat 和 Apache Web Server?

java - 使用 JCreator 将行添加到 JTable

java - MenuInflater 不显示 ActionBar 上的元素

java - 参数动态时如何构建 JPQL 查询?

android - 按钮不显示, Material 主题不工作