【发布时间】:2020-05-24 02:45:30
【问题描述】:
我正在制作一个包含多个文本视图的网格布局。同样的xml代码是:
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alignmentMode="alignMargins"
android:background="@android:color/white"
android:columnCount="1"
android:columnOrderPreserved="false"
android:rowCount="1">
<LinearLayout
android:id="@+id/row1"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:background="@android:color/white"
android:weightSum="5">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/background_black"
android:clickable="true"
android:gravity="center"
android:onClick="onClick"
android:textColor="@android:color/black"
android:textSize="32sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/background_black"
android:clickable="true"
android:gravity="center"
android:onClick="onClick"
android:textColor="@android:color/black"
android:textSize="32sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/background_black"
android:clickable="true"
android:gravity="center"
android:onClick="onClick"
android:textColor="@android:color/black"
android:textSize="32sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/background_black"
android:clickable="true"
android:gravity="center"
android:onClick="onClick"
android:textColor="@android:color/black"
android:textSize="32sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/background_black"
android:clickable="true"
android:gravity="center"
android:onClick="onClick"
android:textColor="@android:color/black"
android:textSize="32sp" />
</LinearLayout>
</GridLayout>
正如您在本文中看到的,对于每个文本视图,我都定义了 onClick 方法。点击的处理方式如下:
public void onClick(View v) {
if (v instanceof TextView && isInitiatePhase) {
((TextView) v).setText(String.valueOf(++count));
if (count == 5) {
isInitiatePhase = false;
}
} else if (v instanceof TextView) {
// now we have to start cutting/setting the color to red
((TextView) v).setTextColor(Color.RED);
}
}
启动处理得很好,现在在启动阶段之后,当我单击TextViews 时,我想知道单击了哪个。有没有办法在 onClick() 方法中找到类似 TextView 的索引?
LinearLayout 是否提供该功能,如果 TextView 不提供?
另外,我的方法在这里正确吗?还是我应该使用其他布局?
【问题讨论】:
标签: android textview onclicklistener