【问题标题】:how to change text in textview after clicking on listview item?单击listview项目后如何更改textview中的文本?
【发布时间】:2013-11-13 02:09:38
【问题描述】:

我是安卓编程新手。对于我的 android 应用程序,我想要做的是当用户单击 listView 中的项目时,会打开一个带有项目文本标题的新页面。这是我的代码:

protected void onListItemClick(ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    TextView tv = (TextView)findViewById(R.id.TextView1);
    tv.setText("Some new text");
    Intent intent = new Intent(TypeListActivity.this, List_vaccine_info.class );
    startActivity(intent);
    //Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}

但它不会运行。当我删除时:

TextView tv = (TextView)findViewById(R.id.TextView1);
    tv.setText("Some new text");

它有效,但这不是我想要的,我想根据用户单击的 listView 中的项目文本更改标题 任何帮助将不胜感激

【问题讨论】:

  • 它不会运行是什么意思?您是否遇到崩溃或编译错误?您的布局是否膨胀,其中包含“TextView1”?
  • TypeListActivity.class或List_vaccine_info.class中的textview在哪里
  • 看起来当您单击列表项时,它正在尝试立即添加文本。这段文字应该来自哪里?

标签: android android-listview textview


【解决方案1】:

如果您为 textview 中的每个项目(以及默认的 ArrayAdapter)使用一些默认布局,则需要更改 ArrayAdapter 正在使用的 ArrayList 中的字符串。

如果您使用的是自定义布局,您仍然需要执行上述操作并让您的 getView() 方法获取该项目中的 TextView 并设置其文本。

【讨论】:

    【解决方案2】:

    你必须实现 onItemClick 才能获得点击的项目:

       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
             String text = ArrayList.get[arg2];  //where arg2 is position where you had click and ArrayList is List with which you have initialized your Listview 
    
              Intent i=new Intent(this,NextActivity.class);
              i.putExtra("Text",text);            
              startActivity(i);
    
        }
    

    在下一个屏幕中,在 onCreate() 方法中使用此代码:

          Bundle extras = getIntent().getExtras();
          String title=extras.getString("Text");
          setTitle(title);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多