我正在尝试为我正在制作的 Android 应用程序动态添加和删除 TextView,但我遇到了设置和获取 TextView id 的困难。我似乎在最后两行代码(et.setText 和 ll.removeView)中遇到了空指针异常。有人对如何动态设置和获取文本视图的 id 有任何建议吗?显然 .setId 似乎不起作用,或者更有可能的是,我做错了。
//surrounding non-relevant code removed
EditText et = (EditText) view.findViewById(R.id.edittext_tags);
et.setText("");
TextView nTv = new TextView(view.getContext());
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lparams.setMargins(10, 0, 0, 0);
nTv.setLayoutParams(lparams);
nTv.setId(tag_id);
nTv.setText(str.substring(0, str.length()-1));
nTv.setTextColor(Color.BLUE);
nTv.setTextSize(20);
final LinearLayout linl = (LinearLayout) view.findViewById(R.id.linear_layout_tags);
linl.addView(nTv);
nTv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText et = (EditText) view.findViewById(R.id.edittext_tags);
TextView t = ((TextView)v);
et.setText(t.getText().toString());
linl.removeView(v);
}
});
The TextView
不包含布局中的所有子级,LinearLayout
做。制作linl
final
,然后你可以使用它nTV
's OnClickListener
(只要view
包含布局。如果没有,您将需要做出一些关于您到底想要实现什么的决定 - 尽早参考布局可能会起作用)。
final LinearLayout linl = (LinearLayout) view.findViewById(R.id.linear_layout_tags);
linl.addView(nTv);
nTv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText et = (EditText) linl.findViewById(R.id.edittext_tags);
TextView t = ((TextView)v);
et.setText(t.getText().toString());
linl.removeView(v);
}
按照您的方法,实际上并不需要 id,因为您始终拥有对视图的引用。
但是,如果您想使用视图(非常多余的示例,但这是为了解释):
nTv.setId(tag_id);
linl.addView(nTv);
TextView duplicateTextViewReference (TextView) linl.findViewById (tag_id);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)