从动态创建的适配器列表视图中获取Android getText

时间:2014-01-17 14:23:55

标签: android textview gettext

我有一个自定义适配器列表视图。其布局如下

RelativeLayout
   LinearLayout
       TextView
       Button

需要在该Button上添加点击事件。在那种情况下,需要从TextView获取文本并将其传递给下一个Activity。

我收到了以下代码

holder.btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View vp) {

        LinearLayout rl = (LinearLayout)vp.getParent();
        TextView tv = (TextView)rl.findViewById(R.id.name);
        String text = tv.getText().toString();

    }
});

但它在String text = tv.getText().toString();

上崩溃了

有什么想法吗?

更新

01-17 19:59:12.877: E/AndroidRuntime(16659): FATAL EXCEPTION: main
01-17 19:59:12.877: E/AndroidRuntime(16659): Process: com.atc.detectoract, PID: 16659
01-17 19:59:12.877: E/AndroidRuntime(16659): java.lang.NullPointerException
01-17 19:59:12.877: E/AndroidRuntime(16659):    at com.atc.detectoract.CustomAdapter$2.onClick(CustomAdapter.java:129)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at android.view.View.performClick(View.java:4438)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at android.view.View$PerformClick.run(View.java:18422)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at android.os.Handler.handleCallback(Handler.java:733)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at android.os.Looper.loop(Looper.java:136)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at android.app.ActivityThread.main(ActivityThread.java:5017)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at java.lang.reflect.Method.invokeNative(Native Method)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at java.lang.reflect.Method.invoke(Method.java:515)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-17 19:59:12.877: E/AndroidRuntime(16659):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

But it is crashing on String text = tv.getText().toString();

你有NullPointerExceptiontv为空

您可以使用setTaggetTag

holder.btn.setTag(holder.tv.getText().toString()); // set tag 

然后

holder.btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View vp) {

        String value = (String)vp.getTag(); // get tag

    }
});