Как показать текст ArrayAdapter и значок в списке в Android? - PullRequest
2 голосов
/ 17 декабря 2011

Я создаю онлайн медиаплеер. В котором пользователь может создать свой собственный список воспроизведения. Так что для каждого пользователя есть свой список. И в этом списке есть один элемент под названием Quickmix, который является фиксированным и находится в верхней части этого списка. Я хочу показать значок рядом с текстом Quickmix, а также хочу показать значок рядом с именем воспроизводимого списка воспроизведения. для отображения этого списка я создал один ListView в XML-файле. и я создал PlayListActivity.java, который расширяет активность. в этом классе я создал один ArrayAdapter

private ArrayAdapter< String > mPlayListAdapter = null;
private ListView mPlayList = null;
private String[] mPlayListNames = null;

и в методе onCreate мой код похож на

setContentView( R.layout.playlist_layout );

            mPlayList = new String[array.length ];
        for( int i = 0; i < length; i++ )
        {
            mPlayListNames[i] = array[i].mPlayList;
        }
    mPlayList = ( ListView )findViewById( R.id.playList );
    try {
        mPlayListAdapter =
            new ArrayAdapter< String >( this, 
                android.R.layout.simple_list_item_1,
                mPlayListNames );
        mPlayList.setAdapter( mPlayListAdapter );
        mPlayList.setOnItemClickListener( mPlayListListener );
    } catch( Exception e ) {
        Intent nextActivityIntent = new Intent(
            getApplicationContext(),
            Welcome.class );
        finish();
        startActivity( nextActivityIntent );
        return;
    }
/** 
 * Called when user clicks on any playlist name. This listener starts 
 * playback of that playlist.
 */
private OnItemClickListener mPlayListListener =
    new OnItemClickListener()
    {
        public void onItemClick( AdapterView<?> parent, View view,
            int position, long id )
        {
            Intent nextActivityIntent = new Intent( view.getContext(),
                SomeActivity.class );
            //Some code to start SomeActivity
        }
    };

Я не могу расширить ListActivity / any на PlayListActivity.java Я могу только продлить активность.

есть ли решение, как это сделать? I want o/p like this

Ответы [ 2 ]

0 голосов
/ 17 декабря 2011
0 голосов
/ 17 декабря 2011

Вы должны создать свой ListAdapter.Например:

private class EfficientAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Bitmap mIcon1;
    private Bitmap mIcon2;

    public EfficientAdapter(Context context) {
        // Cache the LayoutInflate to avoid asking for a new one each time.
        mInflater = LayoutInflater.from(context);


    }

    /**
     * The number of items in the list is determined by the number of speeches
     * in our array.
     *
     * @see android.widget.ListAdapter#getCount()
     */
    public int getCount() {

        return stations.length;
    }

    /**
     * Since the data comes from an array, just returning the index is
     * sufficent to get at the data. If we were using a more complex data
     * structure, we would return whatever object represents one row in the
     * list.
     *
     * @see android.widget.ListAdapter#getItem(int)
     */
    public Object getItem(int position) {
        return position;
    }

    /**
     * Use the array index as a unique id.
     *
     * @see android.widget.ListAdapter#getItemId(int)
     */
    public long getItemId(int position) {
        return position;
    }

    /**
     * Make a view to hold each row.
     *
     * @see android.widget.ListAdapter#getView(int, android.view.View,
     *      android.view.ViewGroup)
     */

    public View getView(final int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.

        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {

            convertView = mInflater.inflate(R.layout.listitem, null);

            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.

            TextView textView = (TextView) convertView.findViewById(R.id.text1);
            textView.setText(stations[position]);


        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.

        }


        return convertView;
    }



}

Этот адаптер вы можете использовать так:

mPlayList.setListAdapter(new EfficientAdapter(ctx));

И, как вы понимаете, в R.layout.listitem вы можете создать свою кнопку.В методе getView - вы должны обработать эту кнопку.

UPD: Пример использования Bitmap: вы можете добавить это в getView:

ImageView im  = new ImageView(this);
im.setImageBitmap(bitmap);
convertView.addView(im);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...