问题
I’m new to Android and have a simple question. Currently I’m working on a products application that allows users to add, remove and browse variety of products. The application uses a predefined XML-based layout file as a template that fills the entire screen to show the current product details. When the user adds a new product, I want to re-use the same layout file but populate it with the new product’s information. Also, I want to keep the previously added products (e.g. an ArrayList) and the user can browse this list by sliding horizontally (left-to-right or right-to-left). Now, what is the best thing to use to represent each product (View, sub-view, …etc.), and how to reuse the same XML-based layout file to display different products’ details. Please excuse my English and thank you in advance for the help
回答1:
You can create a new class that extends the ArrayAdapter and then override the getView() method to inflate your custom layout. getView() will return the View for a single row. This way you can reuse your layout. So it will look something like:
public class ProductAdapter extends ArrayAdapter<Product> {
private LayoutInflater li;
public ProductAdapter(Context context, List<Product> products) {
super(context, 0, products);
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the product of the position
Product product = getItem(position);
View v = convertView;
if ( v == null ) {
// Your custom layout file for a single row in the list.
v = li.inflate(R.layout.product_row, null);
}
// Populate your view here. Use v.findViewById().
return v;
}
}
To show the list in an ListActivity use:
// The variable products is your initial list of products.
ProductAdapter adapter = new ProductAdapter(this, products);
setListAdapter(adapter);
When you add a product you can add this to your ArrayAdapter by calling either the adapter.add() (if you want to add your product at the end of the list) or insert() (to specify where in the list of products you want to insert the new product) method on the ProductAdapter. Afterwards you can call adapter.notifyDataSetChanged() to notify your adapter that the data has changed and that the list has to be refreshed.
回答2:
What you are describing is implemented by the ViewPager. There's a blog post on the developer site in addition to the API reference.
To implement it, you'll need to create a PagerAdapter
subclass to fill in the details of each view for the ViewPager
.
来源:https://stackoverflow.com/questions/10152823/reuse-an-xml-layout-file-to-show-different-information-android-application