Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to manage Single and Plural string resource in Android

Hi, guys this is small but very useful concept provided by android. Suppose i have dynamic list of books and i want to show string "n book" means if Book list have 1 book then want to print "Found 1 Book" else show "Found n Books". For This functionality we are simply using condition like this.

if(bookList.size()>1){
print("Found 10 Books");
}
else{
print("Found 1 Book");
}

We have better approach to achieve this feature rather than doing this ordinary code. So let's see step by step.

STEP : 1 in string.xml declare your Resource under tag.



name="lbl_found_books">
quantity="one">Found %1$d Book
quantity="other">Found %1$d Books



Here quantity="one" means when quantity is 1 so use single resource and quantity="other" means more than 1 quantity so use Plural String Resource.

STEP : 2 Now in your java code access this resource like this.


textView.setText(getResources().getQuantityString(R.plurals.lbl_found_books, bookList.size(), bookList.size()));

So above line will get resource according to bookList size and no need any conditions.

Share the post

How to manage Single and Plural string resource in Android

×

Subscribe to Android Blog - Latest Android And Kotlin Development News And Tips To Help You Grow Your Programing

Get updates delivered right to your inbox!

Thank you for your subscription

×