我需要将int值i传递给其他类,因为它是来自数据库的id,但它不允许我使用.putExtra传递int值,因为该值需要为int,但如果我声明这个值最终然后它不能再为循环改变了..帮助,谢谢。
final int x = DataBaseHelper.getLastId();
int i = 0;
final TextView[] textViews = new TextView[x];
while (i < x) {
TextView newTextView = new TextView(this);
newTextView.setText(DataBaseHelper.getTitleNow(i + 1) + " \n");
newTextView.setInputType(newTextView.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
newTextView.setLayoutParams(new LayoutParams((LayoutParams.WRAP_CONTENT), ViewGroup.LayoutParams.WRAP_CONTENT));
newTextView.setClickable(true);
newTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
intent.putExtra("ID", i);
startActivity(intent);
finish();
}
});
ll.addView(newTextView, layoutParams);
textViews[i] = newTextView;
i++;
}
答案 0 :(得分:0)
将i
声明为成员变量,您可以在onClick()
public class HistoryActivity extends Activity
{
int i;
public void onCreate(...)
{
...
}
final int x = DataBaseHelper.getLastId(); //not sure where all of this code is but take off the int type here
i = 0;
final TextView[] textViews = new TextView[x];
while (i < x) {
只需在函数之外声明它(通常在类定义之后),然后它就可以在Activity
您还可以使用循环中的其他变量将i
指定为final
变量
while (i < x) {
final int j = i; // use new variable here
TextView newTextView = new TextView(this);
...
newTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
intent.putExtra("ID", j); // use newly defined variable
startActivity(intent);