How to get the id of a dynamically created textview?

大兔子大兔子 提交于 2019-12-23 18:36:18

问题


I'm trying to dynamically add and remove TextView for an android app I'm making but I'm running into difficulty setting and getting the TextView's id. I seem to be getting null pointer exception's for the last two lines of code (et.setText and ll.removeView). Does anyone have any suggestions on how I can dynamically set and get the id of a textview? Apparently .setId doesn't seem to work, or more likely, I'm doing it wrong.

//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);

    }
});

回答1:


The TextView doesn't contain all the children in the layout, the LinearLayout does. Make linl final, then you can use it in nTV's OnClickListener (As long as the view contains the layout. If not, you're going to need to make some decisions about what exactly you want to achieve - making a reference to the layout earlier on might work).

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);
    }

With your approach the id is not really needed, since you always have a reference to the View.

However, if you wanted to work with views (very redundant example, but it's for the sake of explanation):

nTv.setId(tag_id);
linl.addView(nTv);

TextView duplicateTextViewReference (TextView) linl.findViewById (tag_id);


来源:https://stackoverflow.com/questions/14575169/how-to-get-the-id-of-a-dynamically-created-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!