Emil Adz Emil Adz - 21 days ago 7
Android Question

Can't figure out casting in onClick() method

I have written an application that is designed to show report. The first screen of the application is a table that shows info (name, path) of the reports.

So I want to make the row of the table clickable in order to take me to the next screen where the detailed info of the report is displayed, and to know what is the corresponding report for the row. So I wrote my own row:

TableReportRow:

public class TableReportRow extends TableRow {

Report report;

public TableReportRow(Context context, Report report) {
super(context);
this.report = report;
}

public Report getReport() {
return report;
}

public void setReport(Report report) {
this.report = report;
}
}


And then I created the table programmatically:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reports_list_activity_layout);
application = (SGRaportManagerAppObj)getApplication();
reportsRepository = application.reportsRepository.getReportsRepository();
TableLayout table = (TableLayout) findViewById(R.id.tableReportsList);
table.setStretchAllColumns(true);
table.setShrinkAllColumns(true);
final String tag = "tag";

for (int i= 0; i < reportsRepository.size(); i++) {
Report tempReport = reportsRepository.get(i);
TableReportRow row = new TableReportRow(this, tempReport);
// ...

row.addView(tvName);
row.addView(tvPath);
row.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// This is where I need help.
}
});
table.addView(row);
}


Now I need to perform casting for the view in
onClick()
to get the access to the
GetReport()
method to get the actual corresponding report for the row, but I can't seem to get it right. Can some one help me with this one, please? Any help would be appreciated.

Answer

The View parameter in the onClick event is the View that the handler is bound to. So in your case it will be an instance of TableReportRow, hence:

row.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         TableReportRow local = (TableReportRow) v;
    }
});

Alternatively define your row as final in the outer block:

final TableReportRow row = new TableReportRow(this, tempReport);
...
row.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         // row is in scope here
         row.getVirtualChildCount();
    }
});
Comments