【问题标题】:android - Generate Image Views according to the value in a String variableandroid - 根据字符串变量中的值生成图像视图
【发布时间】:2017-08-25 04:29:22
【问题描述】:

我正在开发一个应用程序,我需要根据字符串变量中保存的值生成ImageViews

例如,如果String strNoOfImages = 2,则应在布局内生成 2 个图像视图。

请看下面的代码:

for (int i=0; i < resultArray.length; i++){

            String strElemnet = resultArray[i].toString();
            strNoOfImages = strElemnet.split(";")[2];  // NO OF IMAGES AT INDEX 2 OF ARRAY
            strHeadings = strElemnet.split(";")[1]; // HEADINGS AT INDEX 1 OF ARRAY

           if(strNoOfImages != null){
                 // is this a write method?
                 // if yes, what should i write here?

           }
} 

'strNoOfImages' 包含一个值,如 2,3 或任何其他数字。我只想根据'strNoOfImages'中的值生成图像视图。

另外,我想知道我是否也必须在activity_mail.xml 中创建imageView

如有任何解决方案,请回复。

提前致谢。

【问题讨论】:

    标签: java android arrays android-layout listview


    【解决方案1】:

    我建议你使用GridView

    您可以通过更改 getCount() 方法的返回值来设置要在 GridView 中显示多少张图像。

    【讨论】:

    • 我不能使用 GridView,事实上我想在 'Horizo​​ntalScrollView' 布局中加载图像。
    【解决方案2】:

    您可以在运行时添加 imageView,以便在您的 xml 中采用任何布局,然后在运行时根据您的条件在该布局中添加 imageView。

    for (int i=0; i < resultArray.length; i++){
    
                String strElemnet = resultArray[i].toString();
                strNoOfImages = strElemnet.split(";")[2];  // NO OF IMAGES AT INDEX 2 OF ARRAY
                strHeadings = strElemnet.split(";")[1]; // HEADINGS AT INDEX 1 OF ARRAY
    
               if(strNoOfImages != null){
                        for(int images=0;images<=strNoOfImages;images++){
                          LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.WRAP_CONTENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(20, 10, 20, 10); //optional you can also set more margins 
    
        ImageView imageView = new ImageView(context); //context is the activity context say, this
        imageView.setLayoutParams(lp);
        imageView.setImageResource(R.drawable.ic_launcher);
        linearLayout.addView(imageView); // here linearlayout is the layout whichever you have add in your xml in which you are adding your imageView
    }
                     // is this a write method?
                     // if yes, what should i write here?
    
               }
    }
    

    使用它,您可以根据自己的条件添加任意数量的 Imageview。

    【讨论】:

    • 它在 'images
    • 它是因为你已经采取了“strNoOfImages”的返回类型是字符串,这就是为什么请把它当作 int
    • 或者另一种解决方案是您可以从该字符串中解析整数值
    • 现在例外是'尝试在空对象引用上调用虚拟方法'void android.widget.LinearLayout.addView(android.view.View)'
    • 我应该创建一个适配器类并在 getView() 函数内部的代码中编写这个 for 循环吗??
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多