并感谢您关注我的要求。 我是Andorid Studio的新手,正在开发一个App,它必须显示事件,课程和新闻列表。有一个DrawerLayout,它允许导航到Event,Course和News的区域,每个区域都有每个特定的RecyclerView,但是到home活动中,我必须显示所有项目(Event,Course和News)。 我为每个项目创建一个适配器(因为它们具有不同的属性),并且每个部分(片段)都可以正常工作,但是现在我被主要活动(家庭)所困扰。
以下是解释它们之间差异的模型: 活动
public class Event {
private int id;
private String title;
private String description;
private LocalDateTime startingDate;
private LocalDateTime endingDate;
private String cost;
private String website;
private Category category;
private Venue venue;
private Organizer organizer;
private String status;
private int resImage;
public Event(int id, String title, String description, LocalDateTime startingDate, LocalDateTime endingDate, String cost, String website, Category category, Venue venue, Organizer organizer, int image) {
this.id = id;
this.title = title;
this.description = description;
this.startingDate = startingDate;
this.endingDate = endingDate;
this.cost = cost;
this.website = website;
this.category = category;
this.venue = venue;
this.organizer = organizer;
this.resImage = image;
}
public Event(){}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDateTime startingDate) {
this.startingDate = startingDate;
}
public LocalDateTime getEndingDate() {
return endingDate;
}
public void setEndingDate(LocalDateTime endingDate) {
this.endingDate = endingDate;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Category getCategory() {
return category;
}
public Venue getVenue() {
return venue;
}
public Organizer getOrganizer() {
return organizer;
}
public String getStatus() {
return status;
}
public int getResImage() {
return resImage;
}
}
新闻:
public class News {
private int id;
private String title;
private String content;
private int resImage;
public News(int id, String title, String content, int image) {
this.id = id;
this.title = title;
this.content = content;
this.resImage = image;
}
public News(){}
public int getId(){
return this.id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setDescription(String description) {
this.content = content;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
课程
public Course(int id, String title, String content, float price, LocalDate startingDate, int availablePlace, Teacher teacher, CourseCategory courseCategory, Location location, Duration duration, Level level, int resImage) {
this.id = id;
this.title = title;
this.content = content;
this.price = price;
this.startingDate = startingDate;
this.availablePlace = availablePlace;
this.teacher = teacher;
this.courseCategory = courseCategory;
this.location = location;
this.duration = duration;
this.level = level;
this.resImage = resImage;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public LocalDate getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDate startingDate) {
this.startingDate = startingDate;
}
public int getAvailablePlace() {
return availablePlace;
}
public void setAvailablePlace(int availablePlace) {
this.availablePlace = availablePlace;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public CourseCategory getCourseCategory() {
return courseCategory;
}
public void setCourseCategory(CourseCategory courseCategory) {
this.courseCategory = courseCategory;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Level getLevel() {
return level;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
这里是适配器: EventAdapter
public class EventViewAdapter extends RecyclerView.Adapter<EventViewAdapter.EventViewHolder> {
ArrayList<Event> eventList;
Context context;
public EventViewAdapter(ArrayList<Event> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
TextView startingDate, place, title;
LinearLayout cellLayout;
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
startingDate = eventView.findViewById(R.id.event_starting_date);
place = eventView.findViewById(R.id.event_place);
title = eventView.findViewById(R.id.event_title);
cellLayout = eventView.findViewById(R.id.event_cell_layout);
}
}
@NonNull
@Override
public EventViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
EventViewHolder evh = new EventViewHolder(view);
return evh;
}
@Override
public void onBindViewHolder(@NonNull EventViewHolder holder, int position) {
final String title = eventList.get(position).getTitle();
final String description = eventList.get(position).getDescription();
final String place = eventList.get(position).getVenue().getCity();
final String address = eventList.get(position).getVenue().getAddress();
final String startDate = String.valueOf(eventList.get(position).getStartingDate().toLocalDate());
final String startTime = String.valueOf(eventList.get(position).getStartingDate().getHour() + ":" + String.valueOf(eventList.get(position).getStartingDate().getMinute()));
final String endDate = String.valueOf(eventList.get(position).getEndingDate().toLocalDate());
final String cost = eventList.get(position).getCost();
final String website = eventList.get(position).getWebsite();
final String category = eventList.get(position).getCategory().getName();
final String organizer = eventList.get(position).getOrganizer().getOrganizer();
final String organizerWebsite = eventList.get(position).getOrganizer().getWebsite();
final int image = eventList.get(position).getResImage();
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailEventActivity.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("place", place);
intent.putExtra("address", address);
intent.putExtra("startDate", startDate);
intent.putExtra("startTime", startTime);
intent.putExtra("endDate", endDate);
intent.putExtra("cost", cost);
intent.putExtra("website", website);
intent.putExtra("category", category);
intent.putExtra("organizer", organizer);
intent.putExtra("orgWebsite", organizerWebsite);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
CourseAdapter:
public class CourseViewAdapter extends RecyclerView.Adapter<CourseViewAdapter.CourseViewHolder> {
ArrayList<Course> courseList;
Context context;
public CourseViewAdapter(ArrayList<Course> courseList, Context context) {
this.courseList = courseList;
this.context = context;
}
public CourseViewAdapter(){}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
TextView startingDate, place, title;
LinearLayout courseLinear;
CourseViewHolder(View courseView){
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
startingDate = courseView.findViewById(R.id.course_starting_date);
place = courseView.findViewById(R.id.course_place);
title = courseView.findViewById(R.id.course_title);
courseLinear = courseView.findViewById(R.id.course_cell_layout);
}
}
@NonNull
@Override
public CourseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
CourseViewHolder cvh = new CourseViewHolder(view);
return cvh;
}
@Override
public void onBindViewHolder(@NonNull CourseViewHolder holder, int position) {
final String title = courseList.get(position).getTitle();
final String category = courseList.get(position).getCourseCategory().getName();
final String description = courseList.get(position).getContent();
final String place = courseList.get(position).getLocation().getName();
final String startDate = String.valueOf(courseList.get(position).getStartingDate());
final int availablePlace = courseList.get(position).getAvailablePlace();
final String teacher = courseList.get(position).getTeacher().getName();
final String teacherEmail = courseList.get(position).getTeacher().getEmail();
final String teacherMobile = courseList.get(position).getTeacher().getPhone();
final String duration = courseList.get(position).getDuration().getName();
final String level = courseList.get(position).getLevel().getName();
final String price = String.valueOf(courseList.get(position).getPrice());
final int image = courseList.get(position).getResImage();
holder.courseImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.courseLinear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailCourseActivity.class);
intent.putExtra("title", title);
intent.putExtra("category", category);
intent.putExtra("content", description);
intent.putExtra("startDate", startDate);
intent.putExtra("availablePlace", availablePlace);
intent.putExtra("teacher", teacher);
intent.putExtra("teacherEmail", teacherEmail);
intent.putExtra("teacherMobile", teacherMobile);
intent.putExtra("duration", duration);
intent.putExtra("price", price);
intent.putExtra("place", place);
intent.putExtra("level", level);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return courseList.size();
}
public void courseSetSearchOperation(ArrayList<Course> newList){
courseList = new ArrayList<>();
courseList.addAll(newList);
notifyDataSetChanged();
}
}
新闻:
public class NewsViewAdapter extends RecyclerView.Adapter<NewsViewAdapter.NewsViewHolder> {
ArrayList<News> newsList;
Context context;
public NewsViewAdapter(ArrayList<News> newsList, Context context) {
this.newsList = newsList;
this.context = context;
}
public NewsViewAdapter(){}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
TextView newsTitle, newsContent;
LinearLayout newsLayout;
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
newsTitle = newView.findViewById(R.id.news_title);
newsContent = newView.findViewById(R.id.news_content);
newsLayout = newView.findViewById(R.id.news_cell_layout);
}
}
@NonNull
@Override
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
NewsViewHolder nvh = new NewsViewHolder(view);
return nvh;
}
@Override
public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
final String title = newsList.get(position).getTitle();
final String content = newsList.get(position).getContent();
final int image = newsList.get(position).getResImage();
holder.newsImage.setImageResource(image);
holder.newsTitle.setText(title);
holder.newsContent.setText(content);
holder.newsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailNewsActivity.class);
intent.putExtra("title", title);
intent.putExtra("content", content);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return newsList.size();
}
public void newsSetSearchOperation(ArrayList<News> newList){
newsList = new ArrayList<>();
newsList.addAll(newList);
notifyDataSetChanged();
}
}
每个特定的项目列表都分成一个片段,实际上这里是Main Activity(主页),我想在其中显示所有主题的RecyclerView:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView mNavigationView;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private FloatingActionButton fab;
private RecyclerView mRecyclerView;
private ImageView openFilter;
private SearchView searchView;
private DataMock dataMock = new DataMock();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view_main);
drawerLayout = findViewById(R.id.drawer_layout);
mNavigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
openFilter = findViewById(R.id.filter_icon);
searchView = findViewById(R.id.action_search);
fab = findViewById(R.id.fab);
fab.show();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
searchView.setQueryHint(getString(R.string.search_hint));
drawerToggle = setupDrawerToggle();
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
drawerLayout.setDrawerListener(drawerToggle);
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
});
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment nextFragment;
switch (menuItem.getItemId()){
case R.id.event_list:
nextFragment = new EventFragment();
break;
case R.id.course_list:
nextFragment = new CourseFragment();
break;
case R.id.news_list:
nextFragment = new NewsFragment();
break;
default:
throw new IllegalArgumentException("No Fragment for the given menu item");
}
if (nextFragment != null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.anchor_point, nextFragment)
.commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawerLayout.closeDrawer(mNavigationView);
}
return false;
}
});
openFilter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BottomSheetDialog filterDialog = new BottomSheetDialog();
filterDialog.show(getSupportFragmentManager(), "filter dialog opened!");
}
});
// mRecyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// mRecyclerView.setLayoutManager(layoutManager);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
public void backToHome(View view){
for (Fragment fragment : getSupportFragmentManager().getFragments()){
if (fragment != null && (fragment instanceof CourseFragment || fragment instanceof EventFragment || fragment instanceof NewsFragment)){
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
toolbar.setTitle("WePress");
fab.show();
}
}
Toast.makeText(this, "Premuto sul logo", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(mNavigationView);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
public void addItem(View view){
PopupMenu popupMenu = new PopupMenu(MainActivity.this, fab);
popupMenu.getMenuInflater().inflate(R.menu.fab_main_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.add_event:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un evento", Toast.LENGTH_SHORT).show();
Intent intentEvent = new Intent(MainActivity.this, AddItemActivity.class);
intentEvent.putExtra("isFrom", "event");
startActivity(intentEvent);
break;
case R.id.add_course:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un corso", Toast.LENGTH_SHORT).show();
Intent intentCourse = new Intent(MainActivity.this, AddItemActivity.class);
intentCourse.putExtra("isFrom", "course");
startActivity(intentCourse);
break;
case R.id.add_news:
Toast.makeText(MainActivity.this, "Pronti per aggiungere una news", Toast.LENGTH_SHORT).show();
Intent intentNews = new Intent(MainActivity.this, AddItemActivity.class);
intentNews.putExtra("isFrom", "news");
startActivity(intentNews);
break;
}
return true;
}
});
popupMenu.show();
}
}
如果可以显示具有不同布局的列表,您还可以提出一种避免重复代码行来提高代码质量的方法吗?如果我没看错,我想重复使用每个适配器或可以放入特定类(?)的部分适配器。 非常感谢你的帮助! 如果我缺少一些信息,请问我以编辑帖子。
答案 0 :(得分:1)
您只能对一个视图模型类做一个适配器(使用视图类型) 包含事件,新闻或课程
适配器应该是这样的:
public class EventViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_EVENT = 10;
private static final int TYPE_COURSE = 11;
private static final int TYPE_NEWS = 12;
ArrayList<EventViewModel> eventList;
Context context;
public EventViewAdapter(ArrayList<EventViewModel> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
@Override
public int getItemViewType(int position) {
EventViewModel event = eventList.get(position);
if (event.isEvent()) {
return TYPE_EVENT ;
} else if(event.isCourse()) {
return TYPE_COURSE;
} else {
return TYPE_NEWS;
}
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
//....
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
//.....
}
}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
//.....
CourseViewHolder(View courseView) {
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
//.....
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
//.....
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
//.....
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == TYPE_EVENT) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
return new EventViewHolder (rootView);
} else if (viewType == TYPE_COURSE) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
return new CourseViewHolder(rootView);
} else {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
return new NewsViewHolder(rootView);
}
}
@Override
public void onBindViewHolder(@NonNull EventViewHolder holder, int position)
{
final EventViewModel eventViewModel = eventList.get(position);
if (eventViewModel .isEvent()) {
onBindEvent(holder, eventViewModel.getEvent());
} else if(eventViewModel .isCourse()) {
onBindCourse(holder, eventViewModel.getCourse());
} else {
onBindNews(holder, eventViewModel.getNews());
}
}
private void onBindEvent(RecyclerView.ViewHolder holder, Event event) {
EventViewHolder eventHolder= (EventViewHolder ) holder;
final String title = event.getTitle();
final String description = event.getDescription();
// others ...
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
// others ...
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
// ...
}
@Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
还有类似的View Model类:
public class EventViewModel() {
private Event mEvent;
private Course mCourse;
private News mNews;
private EventViewModel(Event event, Course course, News news) {
this.mEvent = event;
this.mCourse = course;
this.mNews = news;
}
public boolean isEvent() {
return mEvent != null
}
public boolean isCourse() {
return mCourse != null
}
public boolean isNews() {
return mNews != null
}
public static EventViewModel getEventInstance(Event event) {
return new EventViewModel(event, null, null
}
public static EventViewModel getCourseInstance(Course course) {
return new EventViewModel(null, course, null
}
public static EventViewModel getNewsInstance(News news) {
return new EventViewModel(null, null, news
}
public Event getEvent() {
return mEvent;
}
public Event getCourse() {
return mScore;
}
public Event getNews() {
return mNews;
}
}
您可以在所有片段(事件,过程,新闻)中使用此适配器,并且每个片段都会污染EventViewModel的列表,其中仅包含其特定类型。主活动中显示的适配器包含用于显示所有事件的所有类型的EventViewModel。