AdapterView.OnItemClickListener传递给新活动

时间:2015-06-25 21:18:16

标签: java android

我是Android编程的新手,我需要一些帮助。我创建了一个列表,这里是代码,我想通过单击列表中的项目来传递给新活动,有人可以建议我如何逐步完成它吗?谢谢!

 package com.example.andrian.testapp;

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.app.Activity;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.AdapterView;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemClickListener;

    import com.example.andrian.testapp.R;


    public class MainActivity extends ActionBarActivity {
        ListView listView ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            listView = (ListView) findViewById(R.id.list);

            String[] values = new String[] {
                    "L0",
                    "L1",
                    "L2",
                    "L3",
                    "L4",
                    "L5",
                    "L6",
                    "L7"
            };


            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, android.R.id.text1,     values);


        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {

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

                int itemPosition = position;

                String itemValue = (String) listView.getItemAtPosition(position);

                Toast.makeText(getApplicationContext(),
                        "Position: " + itemPosition + "  List Item: " + itemValue, Toast.LENGTH_LONG)
                        .show();

            }

        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    }

1 个答案:

答案 0 :(得分:1)

将YOUR_ACTIVITY_NAME替换为新活动的名称

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getApplicationContext(),YOUR_ACTIVIY_NAME.class);
            startActivity(intent);
        }
    });
祝你好运。