Android的 - 确定在ListView项目 [英] android - identify items in a ListView

查看:119
本文介绍了Android的 - 确定在ListView项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在遇到一些麻烦,在正确识别项目的的ListView

有4类说事,这是一个很大code,所以首先我要解释这些类的逻辑。


  • 输入 ListActivity 和初始化其的ListView

  • 执行的AsyncTask 从服务器下载JSON响应,解析它,填充的ListView 使用对象和集合适配器而呈现出 ProgressDialog

  • PlaylistItem 类包括它只是从一个单一的JSONObject获取数据的方法。它被用于参数与其对象ArrayList中

    • 的AsyncTask 完成列表填充项,看起来像|按钮|艺术家(的TextView ) - 标题(的TextView


更新

解决第一期,但仍无法找出什么地方错了按钮

2)。我设置了 OnClickListener 我在适配器的getView()方法的按钮。要找出是否按钮被正确识别我什么也没做,但只是改变了它的背景。但在某按钮的点击的迫使每11日或12日按钮的背景改变。不能弄明白为止。

我不能继续获得URL和流音频,直到这些问题解决了,所以任何帮助是极大的AP preciated。我班下面去,如果事情出现不明请询问。

AudioList

 公共类AudioList扩展ListActivity {
私人的ListView LV;
私人PlaylistLoader装载机;
私人AudioListAdapter适配器;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_audio_list);
    在里面(); //初始化的ListView    / * ---填充列表与用户的情况下,网络连接音频可用--- * /
    装载机=新PlaylistLoader(这一点,LV,适配器);
    如果(Utils.isNetworkAvailable(本)){
        loader.execute();
    }其他{
        APP_CONSTANTS.NO_DATA_CONNECTION(本);
    }}@覆盖
保护无效onResume(){
    super.onResume();
    lv.setOnItemClickListener(新OnItemClickListener(){
        @覆盖
        公共无效onItemClick(适配器视图<>为arg0,ARG1观,诠释ARG2,
                长ARG3){            Toast.makeText(getApplicationContext(),Integer.toString(ARG2)
                    Toast.LENGTH_SHORT).show();
            }
    });}私人无效的init(){
    LV = getListView();
    lv.setTranscriptMode(00000000);
    lv.setDividerHeight(1);
    lv.setSmoothScrollbarEnabled(真);
    lv.setVerticalFadingEdgeEnabled(真);}

PlaylistLoader

 公共类PlaylistLoader扩展的AsyncTask<太虚,太虚,太虚> {私人的JSONObject usersPlaylist,singleJSONItem;
私人JSONArray responseJSONArray;
私人的ListView LV;
私人的ArrayList< PlaylistItem>播放列表;
私人活动;
私人PlaylistItem audioList;
私人共享preferences preFS;
私人ProgressDialog PD;
AudioListAdapter适配器;公共PlaylistLoader(活动一,ListView的LV,AudioListAdapter适配器){
    this.lv = LV;
    this.a =一;
    this.adapter =适配器;
}@覆盖
保护无效doInBackground(虚空......为arg0){
    / * ---创建PlaylistItem对象的新的ArrayList --- * /
    播放列表=新的ArrayList< PlaylistItem>();
    / * ---获得使用电话的活动范围内的preferences --- * /
    preFS = preferenceManager.getDefaultShared preferences(一);
    尝试{
        / * ---从服务器下载响应的JSONObject //的access_token和
         * USER_ID来自活动的defaultShared preferences --- * /
        usersPlaylist = Utils.retrieveJsonObjectFromUrl(新URL(
                APP_CONSTANTS.REQUEST_AUDIO_LIST(preFS)),A);
        / * ---从接收到的对象得到响应阵列--- * /
        responseJSONArray = usersPlaylist.getJSONArray(回应);
        / * ---从响应数组对象填充的ArrayList --- * /
        的for(int i = 0; I< responseJSONArray.length();我++){
            singleJSONItem = responseJSONArray.getJSONObject(ⅰ);
            audioList =新PlaylistItem(singleJSONItem);
            playlist.add(audioList);        }    }赶上(MalformedURLException的E){
        e.printStackTrace();
    }赶上(JSONException E){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }
    返回null;
}@覆盖
在preExecute保护无效(){
    super.on preExecute();
    PD =新ProgressDialog(一);
    pd.setTitle(请稍候);
    pd.setMessage(检索音频列表...);
    pd.show();}@覆盖
保护无效onPostExecute(虚空结果){
    super.onPostExecute(结果);
    lv.setVisibility(View.VISIBLE);
    pd.dismiss();
    / * ---坐落在构造函数中传递的适配器作为传递的ListView适配器--- * /
    适配器=新AudioListAdapter(一,R.layout.playlist_item,播放列表);
    lv.setAdapter(适配器);}
    }

AudioListAdapter

 公共类AudioListAdapter扩展ArrayAdapter< PlaylistItem> {
私人PlaylistItem PL;
私人上下文的背景下;
私人诠释layoutResourceId;
私人PlaylistItem澳元;
私人的ArrayList< PlaylistItem>数据= NULL;公共AudioListAdapter(上下文的背景下,INT layoutResourceId,
        ArrayList的< PlaylistItem>数据){
    超级(上下文,layoutResourceId,数据);
    this.layoutResourceId = layoutResourceId;
    this.context =背景;
    this.data =数据;}@覆盖
公共PlaylistItem的getItem(INT位置){
    返回super.getItem(位置);
}@覆盖
公众诠释的getCount(){
    返回data.size();
}@覆盖
公众诠释为getPosition(PlaylistItem项){
    返回super.getPosition(项目);
}@覆盖
公共查看getView(INT位置,查看convertView,父母的ViewGroup){    PL =新PlaylistItem();
    AUD =的getItem(位置);    如果(convertView == NULL){
        LayoutInflater充气=((活动)上下文).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId,父母,假);
        pl.btnPlay =(按钮)convertView.findViewById(R.id.btn_list_play);
        pl.imgSaved =(ImageView的)convertView
                .findViewById(R.id.img_list_audio_saved);
        pl.tvArtist =(TextView中)convertView
                .findViewById(R.id.tvListItemArtist);
        pl.tvTitle =(TextView中)convertView
                .findViewById(R.id.tvListItemSong);        convertView.setTag(PL);
    }其他{
        PL =(PlaylistItem)convertView.getTag();
        pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
    }    pl.tvArtist.setText(aud.getArtist()++ - );
    pl.tvTitle.setText(aud.getTitle());    pl.btnPlay.setOnClickListener(新View.OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            / *如果这个选项在preferences启用---震动--- * /
            如果(APP_CONSTANTS.isHapticFeedbackEnabled(的getContext())){
                APP_CONSTANTS.doVibrate(的getContext());            }
         pl.btnPlay.setBackgroundResource(R.drawable.list_button_pause);        }
    });    返回convertView;
}

PlayListItem

 公共类PlaylistItem {私人字符串艺术家,标题;
私人的JSONObject OBJ;
公共按钮btnPlay;
公众的TextView tvArtist,tvTitle;
公共ImageView的imgSaved;
公众诠释持续时间;
公众诠释audio_id;
公共字符串的URL;/ * ---构造从响应阵列需要一个单一的JSONObject --- * /
公共PlaylistItem(OBJ的JSONObject){
    this.obj = OBJ;
}公共PlaylistItem(){
    //默认的构造函数
}/ * ---下面的返回值的方法,从通过JSONObject的关键--- * /公共字符串getArtist(){
    尝试{
        艺术家= obj.getString(艺术家);
    }赶上(JSONException E){        e.printStackTrace();
    }
    返回的艺术家;}公共字符串的getTitle(){
    尝试{
        标题= obj.getString(标题);
    }赶上(JSONException E){        e.printStackTrace();
    }
    返回称号;
}公众诠释的getID(){
    尝试{
        audio_id = obj.getInt(援助);
    }赶上(JSONException E){        e.printStackTrace();
    }
    返回audio_id;
}公共字符串的getURL(){
    尝试{
        URL = obj.getString(URL);
    }赶上(JSONException E){        e.printStackTrace();
    }
    返回URL;
}
    }


解决方案

  

但在某个按钮的点击的迫使每11日或12日按钮的背景改变。不能弄明白为止。


您是战斗列表视图回收行的布局方式。结果
想想这样说:如果你有1000行的ListView控件,但只能满足其中9个在屏幕上,那么就没有任何意义创建10,000个独特的布局。这只是浪费资源,而不是仅仅的ListView创建〜10的布局和重用他们。

解决方案:返回每个行的时候,它被重新使用默认状态。在 getView()补充:

 }其他{
    PL =(PlaylistItem)convertView.getTag();
    pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
    //我猜在资源的名称^^^^^^^^^^^^^^^^
}

(你也可以做一些小的改动,以加快code。对于例如,你只需要一个OnClickListener,因为它们都含有相同的code,使之成为一个类变量,并把它传递给每个PLAY键。还有更多。)

I'm having some troubles with correct identification of items in a ListView.

There are 4 classes that matter, it's a lot of code so at first I'm going to explain the logic of those classes.

  • Enter the ListActivity and initialize its ListView
  • execute an AsyncTask that downloads JSON response from the server, parses it, populates the ListView with Objects and sets the adapter while showing a ProgressDialog
  • the PlaylistItem class includes methods which simply get the data from a single JSONObject. It is used to parameterize the ArrayList with its Objects
    • after the AsyncTask is done the list is filled with items and looks like |Button| Artist(TextView) - Title(TextView)

UPDATE

resolved 1st issue but still can't figure out what's wrong with buttons

2). I set an OnClickListener to my buttons in the Adapter's getView() method. To find out if the button is identified correctly I did nothing but just changed its background. BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.

I can't proceed to getting url and streaming audio until those problems are resolved, so any help is greatly appreciated. My classes go below, please ask if something appears unclear.

AudioList

         public class AudioList extends ListActivity {
private ListView lv;
private PlaylistLoader loader;
private AudioListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_list);
    init(); // initialize the ListView

    /*--- populate the list with user's audio in case network connection is available ---*/
    loader = new PlaylistLoader(this, lv, adapter);
    if (Utils.isNetworkAvailable(this)) {
        loader.execute();
    } else {
        APP_CONSTANTS.NO_DATA_CONNECTION(this);
    }

}

@Override
protected void onResume() {
    super.onResume();
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Toast.makeText(getApplicationContext(), Integer.toString(arg2),
                    Toast.LENGTH_SHORT).show();
            }
    });

}

private void init() {
    lv = getListView();
    lv.setTranscriptMode(0x00000000);
    lv.setDividerHeight(1);
    lv.setSmoothScrollbarEnabled(true);
    lv.setVerticalFadingEdgeEnabled(true);

}

PlaylistLoader

      public class PlaylistLoader extends AsyncTask<Void, Void, Void> {

private JSONObject usersPlaylist, singleJSONItem;
private JSONArray responseJSONArray;
private ListView lv;
private ArrayList<PlaylistItem> playlist;
private Activity a;
private PlaylistItem audioList;
private SharedPreferences prefs;
private ProgressDialog pd;
AudioListAdapter adapter;

public PlaylistLoader(Activity a, ListView lv, AudioListAdapter adapter) {
    this.lv = lv;
    this.a = a;
    this.adapter = adapter;
}

@Override
protected Void doInBackground(Void... arg0) {
    /*--- create new ArrayList of PlaylistItem Objects ---*/
    playlist = new ArrayList<PlaylistItem>();
    /*--- get the preferences using context of calling activity ---*/
    prefs = PreferenceManager.getDefaultSharedPreferences(a);
    try {
        /*--- download the response JSONObject from server // access_token and 
         * user_id come from activity's defaultSharedPreferences ---*/
        usersPlaylist = Utils.retrieveJsonObjectFromUrl(new URL(
                APP_CONSTANTS.REQUEST_AUDIO_LIST(prefs)), a);
        /*--- get the response array from received object ---*/
        responseJSONArray = usersPlaylist.getJSONArray("response");
        /*--- populate the ArrayList with Objects from the response array ---*/
        for (int i = 0; i < responseJSONArray.length(); i++) {
            singleJSONItem = responseJSONArray.getJSONObject(i);
            audioList = new PlaylistItem(singleJSONItem);
            playlist.add(audioList);

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pd = new ProgressDialog(a);
    pd.setTitle("Please wait");
    pd.setMessage("Retrieving audio list...");
    pd.show();

}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    lv.setVisibility(View.VISIBLE);
    pd.dismiss();
    /*--- set the adapter passed in constructor as an adapter for passed ListView ---*/
    adapter = new AudioListAdapter(a, R.layout.playlist_item, playlist);
    lv.setAdapter(adapter);

}
    }

AudioListAdapter

           public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;

public AudioListAdapter(Context context, int layoutResourceId,
        ArrayList<PlaylistItem> data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;

}

@Override
public PlaylistItem getItem(int position) {
    return super.getItem(position);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public int getPosition(PlaylistItem item) {
    return super.getPosition(item);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    pl = new PlaylistItem();
    aud = getItem(position);

    if (convertView == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId, parent, false);
        pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
        pl.imgSaved = (ImageView) convertView
                .findViewById(R.id.img_list_audio_saved);
        pl.tvArtist = (TextView) convertView
                .findViewById(R.id.tvListItemArtist);
        pl.tvTitle = (TextView) convertView
                .findViewById(R.id.tvListItemSong);

        convertView.setTag(pl);
    } else {
        pl = (PlaylistItem) convertView.getTag();
        pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
    }

    pl.tvArtist.setText(aud.getArtist() + " " + "-");
    pl.tvTitle.setText(aud.getTitle());

    pl.btnPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*--- vibrate if this option is enabled in the preferences ---*/
            if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
                APP_CONSTANTS.doVibrate(getContext());

            }
         pl.btnPlay.setBackgroundResource(R.drawable.list_button_pause);

        }
    });

    return convertView;
}

PlayListItem

     public class PlaylistItem {

private String artist, title;
private JSONObject obj;
public Button btnPlay;
public TextView tvArtist, tvTitle;
public ImageView imgSaved;
public int duration;
public int audio_id;
public String url;

/*--- the constructor takes a single JSONObject from the response array ---*/
public PlaylistItem(JSONObject obj) {
    this.obj = obj;
}

public PlaylistItem() {
    // default constructor
}

/*--- the methods below return values by key from the passed JSONObject ---*/

public String getArtist() {
    try {
        artist = obj.getString("artist");
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return artist;

}

public String getTitle() {
    try {
        title = obj.getString("title");
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return title;
}

public int getID() {
    try {
        audio_id = obj.getInt("aid");
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return audio_id;
}

public String getURL() {
    try {
        url = obj.getString("url");
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return url;
}
    }

解决方案

BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.

You are fighting the way ListViews recycle the row layouts.
Think of it this way: if you have a ListView with 10,000 rows but can only fit 9 of them on the screen, then it doesn't make sense to create 10,000 unique layouts. This just waste resources, instead ListView only creates ~10 layouts and reuses them.

Solution: return each row to it's default state when it is reused. In getView() add:

} else {
    pl = (PlaylistItem) convertView.getTag();
    pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
    // I guessed at the resource's name         ^^^^^^^^^^^^^^^^
}

(Also you can make a few small changes to speed up your code. For instance, you only need one OnClickListener since they all contain the same code, make this a class variable and pass this to each play Button. There are more.)

这篇关于Android的 - 确定在ListView项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆