У меня есть ситуация, в которой мне нужен совет. У меня есть приложение, которое имеет расширяемое представление списка. Каждый дочерний щелчок посылает пользователя к следующему действию, которое представляет собой макет вкладки со списком. Вкладка имеет 3 вкладки. Я пытаюсь выяснить, как отправить данные в список 3-х списков, когда на кнопку click on expandable listview.Использование одного адаптера для нескольких массивов
Первоначально я собирался установить его в setOnChildClickListener так:
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
if (groupPosition == 0) {
if (childPosition == 0) {
mCustomListViewAdapter.addAdapterItem(new CustomObject("Squats", "60%", "6", "150", false));
listViewFri.setAdapter(mCustomListViewAdapter);
EDIT: это моя tablayout деятельность, которая настраивает 3 вкладки. Я не уверен, где можно получить доступ к дополнительным компонентам.
public class WorkoutDaysActivity extends BaseActivity {
ListView listViewFri = (ListView) findViewById(R.id.listViewFri);
ListView listViewMon = (ListView) findViewById(R.id.listViewMon);
ListView listViewWed = (ListView) findViewById(R.id.listViewWed);
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_days);
Bundle extras = getIntent().getBundleExtra("args");
mToolBar = activateToolbarWithHomeEnabled();
setUpNavigationDrawer();
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_workout_days, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
View rootView = inflater.inflate(R.layout.fragment_workout_days, container, false);
Bundle extras = getArguments();
CustomObject objects = (CustomObject) extras.getSerializable("w29w1");
return rootView;
case 2: View rootView2 = inflater.inflate(R.layout.fragment_sub_page1, container, false);
TextView textView2 = (TextView) rootView2.findViewById(R.id.textView2);
textView2.setText("Workout 29 Week 1");
return rootView2;
case 3:
View rootView3 = inflater.inflate(R.layout.fragment_sub_page2, container, false);
TextView textView3 = (TextView) rootView3.findViewById(R.id.txtFrag3);
textView3.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView3;
default: View rootView4 = inflater.inflate(R.layout.fragment_workout_days, container, false);
TextView textView4 = (TextView) rootView4.findViewById(R.id.txtFrag1);
textView4.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView4;
}
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Monday";
case 1:
return "Wednesday";
case 2:
return "Friday";
}
return null;
}
}
}
Я думал, что это будет идти в этой части, как так:
switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
View rootView = inflater.inflate(R.layout.fragment_workout_days, container, false);
Bundle extras = getArguments();
CustomObject objects = (CustomObject) extras.getSerializable("w29w1");
CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, objects);
Но им получает сообщение об ошибке при (это, объекты), говоря «не может быть применен к .placeholderfragment .custom объекта» «PlaceholderFragment не могут быть преобразованы в контексте»
Это то, что я кладу в onChildClick:
Bundle extras = new Bundle();
final ArrayList<CustomObject> objects = new ArrayList<CustomObject>();
objects.add(new CustomObject("Squat", "65%", "6", "150", false));
extras.putSerializable("w29w1", objects);
Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
intent.putExtra("args", extras);
startActivity(intent);
Спасибо за помощь! сообщите мне, если вам нужно увидеть какой-либо из моих кодов, чтобы лучше понять, что я пытаюсь сделать!
Спасибо за ответ. Да, я хочу такое же общее поведение, просто разные наборы данных. Так что, если бы я сделал, как ваш пример myList2.setAdapter (новый MyAdapter), смогу ли я сделать это для как можно большего числа arraylists? Как я могу указать приложение, список которого нужно использовать? Кроме того, я не совсем уверен, как использовать фрагмент.setArguements. Мой вкладка - 3 разных фрагмента. Каждый из них содержит список, который я хочу заполнить указанными аррайалистами. Я также не уверен, где бы я установил адаптеры для заполнения списков. – LBJ33
Будет ли это работать, если я положу что-то вроде намерения.putExtra, чтобы проверить, какая кнопка была нажата? Мне действительно не нужно передавать строку или что-то еще, но если я отправлю строку из childOnClick в раскрывающемся списке, тогда поставьте оператор if, чтобы увидеть, содержит ли это намерение эту строку в классе tablayout, поэтому я знаю, что данные для ввода .. это сработает? Извините трудно объяснить .. имеет больше смысла в моей голове lol – LBJ33
Так что у меня создается впечатление, что каждый фрагмент имеет один ListView (listView). В каждом фрагменте вы вызываете listView.setAdapter (myAdapter), вероятно, в 'onStart()', 'onResume()' или что-то в начале жизненного цикла фрагмента (https://developer.android.com/guide/components/fragments. HTML # Создание). –