我有两个相同列表项的活动我想选择第一个列表项值

时间:2014-01-17 14:26:29

标签: android arrays list

我有两个相同列表项的活动我想要选择第一个列表项值,然后转到同一位置的另一个活动列表项值。我的代码是:

public class First extends Activity{

    ListView lv;

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

        lv=(ListView)findViewById(R.id.listView1);
        String[] values = new String[] {"aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn","oo","pp","qq","rr","ss","tt"};

        ArrayAdapter<String>ad=new ArrayAdapter(this,android.R.layout.simple_list_item_1,values);
        lv.setAdapter(ad);

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

                if(id==1) {   
                } 
            }
        }); 
    } 
}

2 个答案:

答案 0 :(得分:0)

如果我理解你想要什么,在你的OnItemClickListener中,你可以这样做:

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

    String value = values[position];
    Intent intent = new Intent (this, OtherActivity.class);
    intent.putExtra(VALUE_EXTRA_NAME, value);
    intent.putExtra(POSITION_EXTRA_NAME, position);
    startActivity(intent);
}

然后在OtherActivity的onCreate方法中,检索String值和单击项的位置(可以使用setSelection(int position)滚动到相同的位置:

Intent intent = getIntent();
String value = intent.getStringExtra(VALUE_EXTRA_NAME);
int positionClicked = intent.getIntExtra(POSITION_EXTRA_NAME,0);
listView.setSelection(positionClicked);
// do something with the String value

答案 1 :(得分:0)

onItemClick添加

Intent intent = new Intent(First.this, NextActivity.class);
intent.putExtra("position", position);
startActivity(intent);

NextActivity.class

int position;  
Bundle extras = getIntent().getExtras();
if (extras != null) { 
   position= extras.getInt("position"); 
} 
yourListView.setSelection(position);