Несколько цветов текста в списке приложений Android - PullRequest
2 голосов
/ 16 июня 2011

Хорошо, ребята, вот сделка.У меня есть приложение для чтения RSS в моем приложении, которое анализирует XML и разбрасывает его в Listview ... Прямо сейчас у меня установлен зеленый цвет, но мне нужно, чтобы заголовок был зеленым, а часть описания, которую я вставил в каждый из них.строка должна быть черной.

Вот мой код для части, которая отображает канал:

public class CampusNews extends Activity implements OnItemClickListener
{
int checker = RSSHandler.checker;
public final String RSSFEEDOFCHOICE = "myurl";

private static final int SELECT = 0;
private static final int REFRESH = 1;

public final String tag = "RSSReader";
private RSSFeed feed = null;

/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.campus_news_layout);

    // go get our feed!
    feed = getFeed(RSSFEEDOFCHOICE);

    // display UI
    UpdateDisplay();

}


private RSSFeed getFeed(String urlToRssFeed)
{
    try
    {
        // setup the url
       URL url = new URL(urlToRssFeed);

       // create the factory
       SAXParserFactory factory = SAXParserFactory.newInstance();
       // create a parser
       SAXParser parser = factory.newSAXParser();

       // create the reader (scanner)
       XMLReader xmlreader = parser.getXMLReader();
       // instantiate our handler
       RSSHandler theRssHandler = new RSSHandler();
       // assign our handler
       xmlreader.setContentHandler(theRssHandler);
       // get our data via the url class
       InputSource is = new InputSource(url.openStream());
       // perform the synchronous parse           
       xmlreader.parse(is);
       // get the results - should be a fully populated RSSFeed instance, or null on error
       return theRssHandler.getFeed();
    }
    catch (Exception ee)
    {
        // if we have a problem, simply return null
        return null;
    }
}



private void UpdateDisplay()
{
    TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
    TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate);
    ListView itemlist = (ListView) findViewById(R.id.itemlist);


    if (feed == null)
    {
        feedtitle.setText("No RSS Feed Available");
        return;
    }

    // feedtitle.setText(feed.getTitle());
    feedpubdate.setText(feed.getPubDate());




    ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems()){

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // View for custom Background color of feeds
            View view = super.getView(position, convertView, parent);

            if (position % 2 == 0){
                view.setBackgroundColor(0xffe4e4e4); // gray
                ((TextView) view).setTextColor(0xff00DD00); // text color
                ((TextView) view).setTextSize(15.0f);


            } else {
                view.setBackgroundColor(0xffffffff); // White
                ((TextView) view).setTextColor(0xff00DD00); // text color
                ((TextView) view).setTextSize(15.0f);
            }
            return view;
        }


    };




    itemlist.setAdapter(adapter);

    itemlist.setOnItemClickListener(this);

    itemlist.setSelection(0);

}


 @SuppressWarnings("rawtypes")
public void onItemClick(AdapterView parent, View v, int position, long id)
 {
     Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");

     Intent itemintent = new Intent(this,ShowDescription.class);

     Bundle b = new Bundle();
     b.putString("title", feed.getItem(position).getTitle());
     b.putString("description", feed.getItem(position).getDescription());
     b.putString("link", feed.getItem(position).getLink());
     b.putString("pubdate", feed.getItem(position).getPubDate());

     itemintent.putExtra("android.intent.extra.INTENT", b);

     startActivity(itemintent);
 }

}

, и здесь у меня есть код, который говорит ему, как разместить заголовок и описаниекусок внутри каждой строки.

public class RSSItem 
{
private String _title = null;
private String _description = null;
private String _link = null;
private String _category = null;
private String _pubdate = null;


RSSItem()
{
}
void setTitle(String title)
{
    _title = title;
}
void setDescription(String description)
{
    _description = description;
}
void setLink(String link)
{
    _link = link;
}
void setCategory(String category)
{
    _category = category;
}
void setPubDate(String pubdate)
{
    _pubdate = pubdate;
}
String getTitle()
{
    return _title;
}
String getDescription()
{
    return _description;
}
String getLink()
{
    return _link;
}
String getCategory()
{
    return _category;
}
String getPubDate()
{
    return _pubdate;
}
public String toString()
{
    // limit how much text we display
    if (_title.length() > 42)
    {

        return _title.substring(0, 42) + "..." + "\n" +         _description.substring(3, 110) + "...";
    }
    return _title + "\n" + _description.substring(3, 110) + "...";

}
}

Я много искал, и вот как я смог решить большинство своих проблем, но я не смог найти способ поместить несколько цветов текста в одну строку для каждого элемента,Заранее спасибо!

1 Ответ

2 голосов
/ 16 июня 2011

Вы хотите посмотреть на это: http://developer.android.com/resources/faq/commontasks.html#selectingtext.Он охватывает стилизацию частей текста.

РЕДАКТИРОВАТЬ: вы можете использовать экземпляры ForegroundColorSpan , чтобы изменить цвет фрагментов вашего текста.

РЕДАКТИРОВАТЬ # 2: Попробуйтекак то так:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // View for custom Background color of feeds
        View view = super.getView(position, convertView, parent);

        if (position % 2 == 0){
            view.setBackgroundColor(0xffe4e4e4); // gray
            ((TextView) view).setTextColor(0xff00DD00); // text color
            ((TextView) view).setTextSize(15.0f);


        } else {
            view.setBackgroundColor(0xffffffff); // White
            ((TextView) view).setTextColor(0xff00DD00); // text color
            ((TextView) view).setTextSize(15.0f);
        }
        RSSItem item = (RSSItem)getItem(position);
        String title = item.getTitle(), base = item.toString();
        SpannableString str = new SpannableString(base);
        if(title.length() > 42){
           str.setSpan(new ForegroundColorSpan(0xFF00FF00), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
           str.setSpan(new ForegroundColorSpan(0xFF000000), title.length()+1, base.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }else{
           str.setSpan(new ForegroundColorSpan(0xFF00FF00), 0, 45, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
           str.setSpan(new ForegroundColorSpan(0xFF000000), 46, base.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }  
        ((TextView) view).setText(str);
        return view;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...