如何在每行中添加 3 个按钮

我正在写下 Android Studio 应用程序的代码,但是当我测试该函数以检查密码是否正确并在数据库中匹配时,应用程序崩溃了。我已经在以下代码中隔离了问题。如果我从代码中删除此功能,则该应用程序运行良好。


 public String searchPass(String uname, String pass){

    db = this.getReadableDatabase();

    String query= "select uname, pass from" + TABLE_NAME;

    Cursor cursor=db.rawQuery(query, null);

    String a, b;

    b="not found";

    if(cursor.moveToFirst()){

        do{

            a= cursor.getString(0);

            if(a.equals(uname)){

                b=cursor.getString(1);

                break;

            }

        }while(cursor.moveToNext());

    }

    return b;

}


慕村225694
浏览 172回答 3
3回答

森林海

一个简单的答案是在每次迭代中只添加 3 个按钮。我的情况是这是最后一次迭代,添加的按钮更少,只需添加更少:&nbsp; &nbsp; LinearLayout mainLayout = new LinearLayout(this);&nbsp; &nbsp; mainLayout.setOrientation(LinearLayout.VERTICAL);&nbsp; &nbsp; int totalItems = 13;&nbsp; &nbsp; for (int k=0; k<totalItems; k+=3)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; LinearLayout layout = new LinearLayout(this);&nbsp; &nbsp; &nbsp; &nbsp; layout.setOrientation(LinearLayout.HORIZONTAL);&nbsp; &nbsp; &nbsp; &nbsp; layout.setTag(k/3);&nbsp; &nbsp; &nbsp; &nbsp; int numberOfButtonsInRow = (k + 3 < totalItems) ? 3 : totalItems % 3;&nbsp; &nbsp; &nbsp; &nbsp; for(int l = 0; l < numberOfButtonsInRow; l++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Button b = new Button(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.setTag(k + l);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.setText("Button " + (k + l));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; layout.addView(b);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; mainLayout.addView(layout);&nbsp; &nbsp; }此外,我建议将内部循环的内容提取到一个单独的函数中,尽管我将其留在这里是为了使其简短。

慕丝7291255

只需在另一个for循环中的“LinearLayout ll”视图中再添加两个按钮

侃侃无极

解决方案:&nbsp; &nbsp; LinearLayout ll_rootOBJ = findViewById(R.id.ll_root);&nbsp; &nbsp; LinearLayout mainLayout = new LinearLayout(this);&nbsp; &nbsp; mainLayout.setOrientation(LinearLayout.VERTICAL);&nbsp; &nbsp; for (int k=0; k<13; k++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; LinearLayout ll = new LinearLayout(this);&nbsp; &nbsp; &nbsp; &nbsp; ll.setOrientation(LinearLayout.HORIZONTAL);&nbsp; &nbsp; &nbsp; &nbsp; ll.setTag(k);&nbsp; &nbsp; &nbsp; &nbsp; for (int i=1; i<4; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Button b = new Button(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.setTag(k);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.setText("Button");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ll.addView(b);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; mainLayout.addView(ll);&nbsp; &nbsp; }&nbsp; &nbsp; ll_rootOBJ.addView(mainLayout);这将给出你想要的。快乐编码..这是你想要的吗?(在这张图中)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java