2013-01-19 46 views
0

我正在制作一个Android应用程序,并且在我的活动中,我执行了一个对数据库的查询并取得结果。我将结果和TextView添加到Activity中。我希望当我点击TextView,传递给下一个活动餐厅的名称,我点击。我的代码的问题是,它为所有的TextViews保存最后一个餐厅的名称。有任何想法吗?谢谢!生成带有循环的TextViews并为每个生成点击

public class ViewRestaurants extends Activity{ 
String name; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.row_restaurant); 

DBAdapter db = new DBAdapter(this); 
db.open(); 

Cursor c = db.getSpRestaurants(getIntent().getStringExtra("city"), getIntent().getStringExtra("area"), getIntent().getStringExtra("cuisine")); 

View layout = findViewById(R.id.items); 

if(c.moveToFirst()) 
{ 
    do{ 
     name = c.getString(0); 
     TextView resname = new TextView(this); 
     TextView res = new TextView(this); 
     View line = new View(this); 

     resname.setText(c.getString(0)); 
     resname.setTextColor(Color.RED); 
     resname.setTextSize(30); 
     resname.setTypeface(null,Typeface.BOLD); 

     res.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
     res.setText(c.getString(1)+","+c.getString(2)+","+c.getString(3)+"\n"+c.getString(4)); 
     res.setTextSize(20); 
     res.setTextColor(Color.WHITE); 
     res.setClickable(true); 
     res.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(); 
       i.setClassName("com.mdl.cyrestaurants.guide", "com.mdl.cyrestaurants.guide.RestaurantDetails"); 
       i.putExtra("name",name); 
       startActivity(i); 
      } 
     }); 

     line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,2)); 
     line.setBackgroundColor(Color.RED); 

     ((LinearLayout) layout).addView(resname); 
     ((LinearLayout) layout).addView(res); 
     ((LinearLayout) layout).addView(line); 
    }while (c.moveToNext()); 

} 

    db.close(); 
} 

}

回答

0

你需要让你的name最终你的循环中,为了使用它在OnClickListener你的方式删除它作为一类领域。

if(c.moveToFirst()) 
{ 
    do{ 
     final String name = c.getString(0); 

     //other code ... 

     res.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(); 
       i.setClassName("com.mdl.cyrestaurants.guide", "com.mdl.cyrestaurants.guide.RestaurantDetails"); 
       i.putExtra("name",name); 
       startActivity(i); 
      } 
     }); 

     //more code... 

    }while (c.moveToNext()); 
} 
+0

谢谢,问题解决了:) – nestorasg

0

尝试做了这些改变

String name = c.getString(0); 
resname.setText(name); 

它之所以被设定为最后的餐厅名字是因为字符串是通过引用而不是通过值,因为它是一个传入的对象。在do while循环的范围内创建一个唯一的字符串应该解决这个问题。

+0

如果我这样做然后onClick()函数不会识别“名称” – nestorasg