Android:组元素(TextView),因此他们共享一个onClick

问题描述 投票:0回答:2

我正在制作一个数独游戏应用程序,我创建了一个带有81个单独TextView的TableLayout来表示每个方块。

现在的问题是,我希望用户能够选择一个正方形,然后选择一个数字放入他们选择的方格。有什么方法可以将它们组合在一起,然后获取它们单击的单个TextView吗?

也许是这样的:

TextView selected;
table.setOnClickListener(new TableLayout.OnClickListener() {
    ***selected = (TextView) table.getSelectedElement() ?***
}

这样,当他们选择一个数字我就可以:

number.setOnClickListener(new Button.OnClickListener() {
    selected.setText( number.getText().toString() );
}

这样,我就不必为每个方块制作81个单独的onClick方法,我相信这不是解决方案。

在此先感谢您的帮助。

android android-layout textview onclicklistener
2个回答
1
投票

假设您正在使用行,您可以尝试以下方法:

int count = table.getChildCount();
for(int i = 0; i < count; i++){ 
    final View row = table.getChildAt(i);
    for(int j = 0; j < row.getChildCount()){
        TextView textView = (TextView) row.getChildAt(j); 
        textView.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick (View v) {
                    //write some custom alert box that allows use to enter
                    //text. positive alert button should do the follow
                    v.setText(theResult);    
                }
            }
    }
}

你可以优化代码...我已经直接写入stackoverflow所以抱歉,如果我有错误。

还使用GridView的cosider


0
投票

您可以通过在xml中添加onClickListener属性将android:onClick="onClick"设置为任何View。在这种情况下,育儿活动必须具有一个功能

public void onClick(View v) {
}

这将被称为。参数View v是对单击的视图的引用。

正如@royB所提到的,如果用GridView实现表,你会节省很多工作。

© www.soinside.com 2019 - 2024. All rights reserved.