我在android上为我的wordsearch app创建了一个动态编程的tablelayout。这是代码:
public void createGrid(char[][] input) {
TableLayout table = (TableLayout) findViewById(R.id.mainLayout);
Typeface font = Typeface.createFromAsset(getAssets(), "kg.ttf");
for (int i = 0; i < input.length; i++) {
LinearLayout rowLayout = new LinearLayout(this);
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
rowLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
final TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_HORIZONTAL);
for (int j = 0; j < input.length; j++) {
final TextView text = new TextView(this);
Character temp = input[i][j];
text.setTag(i);
text.setText(temp.toString());
text.setPadding(20, 20, 20, 20);
text.setTag(i);
text.setTextSize(txtSize);
text.setTypeface(font);
text.setGravity(Gravity.CENTER);
row.addView(text);
}
table.addView(row);
table.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = motionEvent.getX();
startY = motionEvent.getY();
Log.e("DOWN", "DOWN");
break;
case MotionEvent.ACTION_MOVE:
endX = motionEvent.getX();
endY = motionEvent.getY();
Log.e("MOVE", "MOVE" + " " + view.getTag());
break;
case MotionEvent.ACTION_UP:
endX = motionEvent.getX();
endY = motionEvent.getY();
Log.e("UP","UP " + view.getTag());
break;
}
return true;
}
});
}
}
正如你所看到的,我在桌子上放了一个触摸事件。但输出返回:
E/DOWN: DOWN E/MOVE: MOVE null E/MOVE: MOVE null E/MOVE: MOVE null E/UP: UP null
我尝试将table.setTag(1)
放在我的TableLayout上,我看到触摸真正返回的是TableLayout的标记,而不是动态创建的TextView的标记。
有没有办法检测那些文字视图?
非常感谢任何帮助。
如果有重复的问题,请告诉我。
非常感谢评论,答案和建议。
修改
因为我想在textViews
的每个单元格上检测到tableLayout
,并获取所选textViews中的值以创建字符串。如果该字符串将等于txt
文件中的一个值,则会在tablelayout
上绘制一条线。
修改
我尝试修改表格的onTouch()
方法:
就像这样:
table.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
for (int i = 0; i < table.getChildCount(); i++) {
TextView v = (TextView)row.getChildAt(i);
String tv = v.getText().toString();
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = motionEvent.getX();
startY = motionEvent.getY();
Log.e("DOWN", "DOWN");
break;
case MotionEvent.ACTION_MOVE:
endX = motionEvent.getX();
endY = motionEvent.getY();
Log.e("MOVE", "MOVE " + tv);
break;
case MotionEvent.ACTION_UP:
endX = motionEvent.getX();
endY = motionEvent.getY();
Log.e("UP", "UP " + tv + table.getChildCount());
break;
}
}return true;
}
});
但它只检测到TableLayout
的最后一行。
我希望onTouch()
方法做的是检测行内的TextViews
并更改被触摸/刷过的TextViews
的文本颜色和背景颜色。