简体   繁体   English

单击列表视图项后如何更改文本视图中的文本?

[英]how to change text in textview after clicking on listview item?

I am new to android programming. 我是android编程的新手。 For my android app what I want to do is when a user clicks on an item in listView, a new page is opened with a title of the item's text. 对于我的Android应用程序,我想要做的是当用户单击listView中的项目时,将打开一个新页面,其中带有该项目的文本标题。 here is my code: 这是我的代码:

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

but it won't run. 但它不会运行。 when I remove: 当我删除:

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

it works but this isn't what I want, I want to change the title based on the item's text in listView that the user clicked any help would be appreciated 它有效,但这不是我想要的,我想根据用户单击任何帮助的listView中项目的文本更改标题

If you are using some default layout for each item in the textview (and a default ArrayAdapter), you need to change the string that is in the ArrayList that the ArrayAdapter is using. 如果您为文本视图中的每个项目(以及默认的ArrayAdapter)使用某种默认布局,则需要更改ArrayAdapter所使用的ArrayList中的字符串。

If you are using a custom layout, you still need to do the above and have your getView() method get the TextView in that item and set its text. 如果使用自定义布局,则仍然需要执行上述操作,并让getView()方法获取该项目中的TextView并设置其文本。

You have to implement onItemClick to get clicked item: 您必须实现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);

    }

In Next Screen,use this code in onCreate() method: 在下一屏幕中,在onCreate()方法中使用以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM