简体   繁体   中英

Getting the position of a list item in Android

So I have this class here:

package phil.droid.game;


import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class GameList extends GamesTrialActivity
{

private ListView lv1;
protected String Game_names[]={"God of War","FOS RO DAH", "dhwaud"};
private String Game_pics[]={"God of War","God of War II"};
private int pos;
public void onCreate(Bundle savedInstanceState) 
{   
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gamelist);
    lv1=(ListView)findViewById(R.id.thegamelist);

   lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Game_names));
   lv1.setOnItemClickListener(new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {


                    pos = position;       
                Intent i = new Intent(GameList.this, game_viewer.class);
                startActivity(i);

            }
    });


}               
}

And then this VclassV extends the one ^above^

package phil.droid.game;

import android.os.Bundle;
import android.widget.TextView;
public class game_viewer extends GameList
{


    public void onCreate(Bundle savedInstanceState)
    {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.game_template);

            TextView game_title = (TextView)findViewById(R.id.GameTitle);
            game_title.setText("" + pos);
    }
}

The problem is at the moment that the last bit recognizes "pos" as "0" no matter what option I click on. Can someone suggest a way to make it so pos is recognized as the number element that's clicked on in the previous class?

使pos protected ,而不是private

What you're trying to do can't work: The newly launched activity will not share the same storage as the parent, even if they inherit. The only way it would be possible is if the value was static, but that's not a good idea either.

What you should do instead is to send the data as part of the intent before starting the activity, eg:

intent.putExtra("pos", position);

and then you can pull it out in the new activity with

getIntent().getIntExtra("pos", -1); // -1 is used as default value

Also, game_viewer should most likely be a separate activity, rather than inherit from GameList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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