SetImageDrawable in a list view

醉酒当歌 提交于 2019-12-11 12:45:13

问题


In my list view, I want to make it so that it will change the drawable in the image view i made, but I get an error every time I run it.

ImageView Player;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Player = (ImageView)findViewById(R.id.bob);
    setListAdapter(new ArrayAdapter<String>(this, R.layout.pointguards, PointGuards));
    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view, int position, long id) {
                    String item = (String) lv.getAdapter().getItem(position);
                    //decide how to launch `Intent` depending on `item`
                    if (item == "bob"){
                Intent intent = new Intent("com.example.nba.playerinfo");
                startActivity(intent);
                Player.setImageDrawable(R.drawable.joe);
        }
    };   

This runs perfectly, but when I add the setImageDrawable it crashes. EDIT: The drawable that I would like to change is in the intent that I am going to


回答1:


You need to set the image drawable in the Activity that you are launching with your Intent, not in the ListView. You could pass the name in with intent.putExtras("name", name);. Then in the Activity use setImageDrawable based on the name that you get from the Intent extra.

EDIT: Retrieving data from the Intent in your Activity:

Intent intent = getIntent();
String name = intent.getStringExtra("name");

And then something like this to set the Player ImageView:

if (name.equalsIgnoreCase("joe")
    Player.setImageDrawable(R.drawable.joe);



回答2:


You are not setting your content view. You should set as:

ImageView player;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.your_list_layout);   //   <-- setting content view
  player = (ImageView)findViewById(R.id.bob);
.
.
.


来源:https://stackoverflow.com/questions/9472651/setimagedrawable-in-a-list-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!