动态添加按钮eventListener

时间:2012-10-19 13:10:44

标签: android database sqlite dynamic event-listener

我有代码,我需要获取数据的ArrayList(从SQLite数据库返回)并通过下面的代码将其转换为表。我想知道的是我如何将clickListener添加到我动态添加到表中的按钮?基本上它会将行中其中一列的值添加到我在其他地方访问的SharedPreference变量中。

如果需要更多信息,请告诉我,但我认为这是有道理的。

DatabaseHandler db = new DatabaseHandler(TabFragment3.this.getActivity());
List<FoodPoints> foodpoints = db.getAllFoodPoints();

    for (FoodPoints fp : foodpoints) {
        String listFood = fp.getFood();
        String listPoints = Integer.toString(fp.getPoints());
        String listDate = fp.getDate();

        listDate = listDate.substring(0, 12);

        insertRow(tablePoints, listFood, listPoints, listDate);
        // String log = "ID: " + fp.getID() + ", Food: " + fp.getFood() + ", Points: " + fp.getPoints() + ", Date: " + fp.getDate();
        // Log.d("FoodPoints", log);
    }

private void insertRow(TableLayout tablePoints, String tblFoodName, String tblFoodPoints, String tblFoodDate) {
    final TableRow newrow = new TableRow(currentActivity);

     addPlusButtonPointsTable(newrow);
    addTexttoRowswithValues(newrow, tblFoodName, 3);
    addTexttoRowswithValues(newrow, tblFoodPoints, 17);
    addTexttoRowswithValues(newrow, tblFoodDate, 17);
    tablePoints.addView(newrow);
}

...

private void addPlusButtonPointsTable(TableRow newrow) {
    Button plusButton = new Button(currentActivity);
    //plusButton.setBackgroundColor(R.drawable.);
    plusButton.setText("+");
    plusButton.setMinimumWidth(1);
    plusButton.setMinimumHeight(1);
    plusButton.setTextSize(14);

    newrow.addView(plusButton);
}

2 个答案:

答案 0 :(得分:1)

addPlusButtonPointsTable()方法中添加以下行:

plusButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // do what you want
    }
});

答案 1 :(得分:1)

您可以修改addPlusButtonPointsTable()方法,以便在点击Button时获取您希望存储在首选项中的列的值(例如食物名称)(我认为这是什么你不想要吗?)像这样:

private void addPlusButtonPointsTable(TableRow newrow, String foodName) {
    // ...
    // set the data as the tag for the Button
    plusButton.setTag(foodName);
    plusButton.setOnClickListener(mListener);
    // ...
}

这个方法将被调用如下:

addPlusButtonPointsTable(newrow, tblFoodName);

mListener是这样的:

OnClickListener mListener = new OnCLickListener() {

     @Override
     public void onClick(View v) {
         String foodName = (String)v.getTag();
         // store the value.
     }
}

我还建议您在将视图添加到LayoutParamsTableRow添加到TableRow时使用正确的TableLayout

将视图添加到TableRow

newrow.addView(plusButton, new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

TableRow添加到TableLayout

tablePoints.addView(newrow, new Tablelayout.LayoutParams(Tablelayout.LayoutParams.MATCH_PARENT, Tablelayout.LayoutParams.WRAP_CONTENT));

如果您支持的版本低于2.2,请使用FILL_PARENT代替MATCH_PARENT