从选定的ListViewItem文本填充TextView

时间:2014-09-24 21:06:38

标签: java android arrays textview settext

每次单击列表视图中的任何文本时,我都想在新活动的TextView上调用setText。例如,如果我点击listView中包含" Android"我想要" Android"出现在新活动中。

查找以下代码:

public class ThirdMainActivity extends ActionBarActivity {

    ListView lvCourses;
    String[] courses = { "Android", "HTML 5", "J2SE", "JavaScript", "MySQL", "PHP", "CSS", "JQuery", "C#"};

    String[] descr = { "Android Course", "HTML 5 Course", "J2SE Course", "JavaScript Course", "MySQL Course", "PHP Course", "CSS Course", "JQuery Course", "C# Course" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third_main);

    lvCourses = (ListView) findViewById(R.id.lvCourses);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_1, courses); 

    final TextView rr = (TextView)findViewById(R.id.setT);
    lvCourses.setAdapter(adapter);
    lvCourses.setOnItemClickListener(
        new OnItemClickListener() {     

            @Override
            public void onItemClick(AdapterView<?> lv, View view, int position, long id) {

                if(position == 0){
                    rr.setText(""+descr[0]);
                    Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
                    startActivity(e);                        
                }

                if(position == 1){
                    rr.setText(""+descr[1]);
                    Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
                    startActivity(e);
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

您无需检查所有位置状态。只需在 onItemClick()

上执行此操作
rr.setText(descr[position]);
Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
startActivity(e);

如果您想将此数据传递给新活动

rr.setText(descr[position]);
Intent e = new Intent(getApplicationContext(),TeMainActivity.class);
e.putExtra("desc", descr[position])
startActivity(e);