如何使用textview显示从列表视图中选择的项目的值



使用simplesursoradapter,我引发了一个列表视图。我从列表视图中选择一个项目,并将其保存在变量"标题名称"中,并能够在Toast中显示。现在,我希望将"title name"中的这个值传递给文本查看id"textView3",以便它可以在同一活动中显示在屏幕顶部。当我尝试使用以下代码时,在textView.setText(v_titlename);行得到一个NULL指针异常;。

a) TextView ID"TextView"one_answers"textView2"在custom_row.xml 中

b) TextView ID"textView3"在Activity_Out.xml 中

public void onItemClick(AdapterView<?> parent, View view, int position, long thislist) {
    TextView selectedTitle = (TextView)view.findViewById(R.id.textView);
    TextView titlename= (TextView)view.findViewById(R.id.textView2);
    TextView textView = (TextView) findViewById(R.id.textView3);
    v_titlename=titlename.getText().toString();
    textView.setText(v_titlename);
    Toast.makeText(this, titlename.getText() , Toast.LENGTH_LONG).show();
    inputID=selectedTitle.getText().toString(); // the _id of this title is stored in inputID
}

您需要使"textView"成为类上的一个字段,并在活动的onCreate()中调用findViewById()。按照现在的设置方式,textView不为null的唯一方法是将其作为适配器视图的一部分,并且您必须使用view.findViewById()来调用它。假设您说过希望它位于活动的顶部,那么您就把它放错了位置。text视图是活动的一部分,而不是列表。

R.id.textView3是生成类中的唯一整数。因此,它是"有效的",即使它不是该视图的一部分。绊倒了很多人。

    public class SomeActivity extends Activity {
        private TextView textView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.Activity_Out);
            textView = (TextView) findViewById(R.id.textView3);
            // ...
        }
    // ...
    }

最新更新