如何获取动态创建的textview的ID? [英] How to get the id of a dynamically created textview?

查看:124
本文介绍了如何获取动态创建的textview的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为正在制作的Android应用程序动态添加和删除TextView,但是遇到设置困难和获取TextView ID的困难.我似乎在最后两行代码(et.setText和ll.removeView)中得到了空指针异常.有人对我如何动态设置和获取textview的ID有任何建议吗?显然.setId似乎不起作用,或更可能是我做错了.

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

    }
});

推荐答案

TextView并不包含布局中的所有子元素,而LinearLayout包含.制作linl final,然后可以在nTVOnClickListener中使用它(只要view包含布局.如果没有,则需要对确切的内容做出一些决定.您想要达到的目标-早先引用布局可能会起作用).

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

您的方法实际上并不需要ID,因为您始终可以引用View.

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

这篇关于如何获取动态创建的textview的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆