whilc(rs.next()){
data_big_layout = new LinearLayout(this);
data_big_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
data_big_params.setMargins(0,15,0,0);
data_big_layout.setLayoutParams(data_big_params);
data_big_layout.setOrientation(LinearLayout.HORIZONTAL);
data_big_layout.setWeightSum(20);
data_big_layout.setBackgroundColor(Color.WHITE);
data_big_layout.setTag(rs.getInt(1));
data_big_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"ID: "+data_big_layout.getTag(), Toast.LENGTH_LONG).show();
name.setText("Clicked ID: " + data_big_layout.getTag());
}
});
detail_data_layout = new LinearLayout(this);
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,8.0f);
detail_data_layout.setLayoutParams(lparams);
detail_data_layout.setOrientation(LinearLayout.VERTICAL);
detail_data_layout.setPadding(50,0,0,0);
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
name = new TextView(this);
name.setLayoutParams(lparams);
name.setText("ID(get from rs.next): " + rs.getString(1));
name.setTextSize(24);
name.setTypeface(Typeface.DEFAULT_BOLD);
detail_data_layout.addView(name);
scroll_view_child.addView(data_big_layout); //scroll_view_child is a LinearLayout
}
大家好,我有一个问题无法解决。上面的代码将使用onclick函数生成两个LinearLayout。但是,onclick函数无法识别我被单击了哪一个。
在第一个和第二个LinearLayout中,我设置的两个标记应该分别为“ 1”和“ 2”,但是当我单击它时,所有LinearLayout都将显示为“ 2”。我怎么解决这个问题?谢谢!
我修改了一些测试代码,rs.next肯定可以得到ID“ 1”和“ 2”,但是当我单击LinearLayout(无论单击哪种布局)时,只有第二个将更改Textview。 此外,无论我单击哪个LinearLayout,getTag()都仅显示“ 2”。
ps:跳过了一些textview和imageview代码
点击前
点击后(无论我单击哪种布局):
答案 0 :(得分:0)
不要依赖LinearLayout
变量名来获取标签值。相反,您需要依靠内部点击监听器方法中的View
:
data_big_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"ID: "+ v.getTag(), Toast.LENGTH_LONG).show();
name.setText("Clicked ID: " + v.getTag());
}
});