感兴趣主题:Android
经过数小时的搜索,我无法找到或理解如何动态创建ImageView来存储关联数据并根据单击的图像视图执行操作。
我来详细说明一下,
我正在使用GridLayout创建一个ImageViews网格(因为gridview示例对我来说太复杂了)。我可以创建网格,但仍在努力解决对齐问题。
现在我有了这个ImageViews网格,但是根据我所了解的,这些ImageViews的Id在运行时被转换成整数。但我需要这些ID,因为我使用它们从服务器获取数据,这取决于它们的唯一性。有没有办法在ImageView标签中存储id以外的其他数据?。我来自一个web开发背景,在那里我可以很容易地使用JavaScript创建带有动态id的元素,以便以后在查询中引用和使用。所以请引导我。
public class Exam_Screen extends AppCompatActivity {
GridLayout gridLayout;
public int[] QArray;
private int[] GetQuestionsFromServer() {
return new int[50];
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam__screen);
QArray = GetQuestionsFromServer();
AddQuestionsToScrollArea(QArray);
}
public void AddQuestionsToScrollArea(int[] QArray)
{
gridLayout = findViewById(R.id.gridlayout);
gridLayout.removeAllViews();
int total = QArray.length;
int column = 4 ;
int row = total / column;
gridLayout.setColumnCount(column);
gridLayout.setRowCount(row + 1);
//gridLayout
for (int i = 0, c = 0, r = 0; i < total; i++, c++) {
if (c == column) {
c = 0;
r++;
}
ImageView oImageView = new ImageView(this);
oImageView.setScaleX(0.3f);
oImageView.setScaleY(0.3f);
oImageView.setId(i); // I want to set the Ids I get from Server, and use them later
oImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
oImageView.setAdjustViewBounds(true);
oImageView.setImageResource(R.drawable.new_candidate_image);
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.width = 30;
lp.height = 30;
lp.topMargin = 5;
lp.bottomMargin = 5;
lp.leftMargin = 5;
lp.rightMargin = 5;
oImageView.setLayoutParams(lp);
GridLayout.Spec rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
GridLayout.Spec colspan = GridLayout.spec(GridLayout.UNDEFINED, 1);
if (r == 0 && c == 0) {
Log.e("", "spec");
Log.d("Column", "value: " + column);
Log.d("rows", "value: " + row);
colspan = GridLayout.spec(GridLayout.UNDEFINED, 1);
rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
}
GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(
rowSpan, colspan);
gridLayout.addView(oImageView, gridParam);
}
}
}
相关检查屏幕活动XML
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border">
android:id="@+id/gridlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>