2016-01-15 2 views
0

Честно говоря, я продумал об этом, прежде чем спрашивать. как получить намерение от активности до fragmentactivity Я пытаюсь использовать viewpager. Я имею здесь ошибку в рассуждениях ПОЛУЧИТЬ Bundle extras = getArguments();Как получить намерение в действии

public class SingleViewActivity extends FragmentActivity { 
    ImageView imageView; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_page_view); 

    ArrayList<Listitem> personArrayList = new ArrayList<Listitem>(); 
     // Listitem item = new Listitem("1", "http://developer.android.com/assets/images/android_logo.png");//I used to add it staticly 

     Bundle extras = getArguments(); 
     if (extras != null) { 
      extras = extras.getParcelableArrayList(ARG_PERSON_LIST); 
      personArrayList.add(item);  } 
    // DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList); 

     ViewPager mViewPager = (ViewPager) findViewById(R.id.pager); 
     Log.d("s", "singleview"); 


     DemoCollectionPagerAdapter mDemoCollectionPagerAdapter =  new DemoCollectionPagerAdapter(getSupportFragmentManager(),personArrayList); 
     mViewPager.setAdapter(mDemoCollectionPagerAdapter); 
+1

'Bundle статистов = getIntent() getExtras()' –

+0

@ cricket_007 спасибо человеку, но я получил ошибку здесь, '= дополнительные extras.getParcelableArrayList (ARG_PERSON_LIST)', что он должен быть? – Moudiz

+0

"extras.getParcelableArrayList (ARG_PERSON_LIST);" возвращает вам ParcelableList, который вы хотите поместить в объект Bundle. Я могу вам сказать, что даже без stacktrace :) – Beemo

ответ

1

Вам понадобятся две операции. Поскольку вы не опубликовали сообщение Activity, которое запустило сообщение Activity, я сделал простой, содержащий только Button, который запустил показанный Activity.

Обратите внимание на прокомментированные шаги. Всего шесть шагов.

Первый Activity получает данные ArrayList, передает его на второй номер Activity, который, в свою очередь, дает DemoCollectionAdapter. .

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_first); 

     Button button = (Button) findViewById(R.id.button); 

     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       // Step 1: Build an ArrayList to pass to the next Activity 
       ArrayList<Listitem> items = new ArrayList<Listitem>(); 
       items.add(new Listitem("1", "http://developer.android.com/assets/images/android_logo.png")); 
       items.add(new Listitem("2", "https://i.stack.imgur.com/B28Ca.jpg?s=328&g=1")); 

       // Step 2: Create an Intent to start the next Activity 
       Intent intent = new Intent(getApplicationContext(), SingleViewActivity.class); 

       // Step 3: Put the ArrayList into the Intent 
       intent.putParcelableArrayListExtra(SingleViewActivity.ARG_PERSON_LIST, items); 

       // Step 4: Start the next Activity 
       startActivity(intent); 
      } 
     }); 
    } 
} 

public class SingleViewActivity extends FragmentActivity { 
    public static final String ARG_PERSON_LIST = "ARG_PERSON_LIST"; 

    private ArrayList<Listitem> items; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_page_view); 

     // Step 5: Get the Bundle from the Intent that started this Activity 
     Bundle extras = getIntent().getExtras(); 
     if (extras != null) { 
      // Step 6: Get the data out of the Bundle 
      items = extras.getParcelableArrayList(ARG_PERSON_LIST); 
     } else { 
      items = new ArrayList<Listitem>(); 
     } 

     ViewPager pager = (ViewPager) findViewById(R.id.pager); 
     DemoCollectionPagerAdapter adapter = new DemoCollectionPagerAdapter(getSupportFragmentManager(), items); 
     pager.setAdapter(adapter); 

    } 
} 
+0

спасибо, что это сработало. ваш удивительный человек. кстати, я не знаю, нужен ли ему новый вопрос, но я не могу пронести изображение. xml правильный, он содержит viewpager. – Moudiz

+0

Ваш метод 'getCount' в' DemoCollectionPagerAdapter' должен вернуть размер списка вместо 1. Например. 'public int getCount() {вернуть это. personArrayList.size(); } ' –

+0

nop it did not work public int getCount() { return this.personArrayList.size(); } можете ли вы мне помочь? – Moudiz

0

Вы назначаете объект ParcelableList переменной Bundle.

extras = extras.getParcelableArrayList(ARG_PERSON_LIST); //change it 

Назначают его в ParcelableList, а не extras.

EDIT:

Попробуйте это,

ArrayList<Listitem> personArrayList; 
// Listitem item = new Listitem("1", "http://developer.android.com/assets/images/android_logo.png");//I used to add it staticly 

Bundle extras = getArguments(); 
if (extras != null) { 
    personArrayList = (ArrayList<Listitem>) extras.getParcelableArrayList("jh"); 
    personArrayList.add(item); 
    ....  
} 
+0

Прошу прощения, я новичок в android .. к чему его изменить? – Moudiz

+0

Зависит от того, что вы хотите сделать. См. Отредактированный ответ – Msp

+0

, он не работал, ошибка в getarguments() и ниже arraylist, я хочу получить намерение от активности до фрагмента, где находится элемент? – Moudiz

0

Когда вы создаете свой объект фрагмента, вы также установили аргумент в созданный объект фрагмента.

Что-то вроде этого ...

Fragment f = new Fragment(); 
Bundle args = new Bundle(); 
args.putInt("someNum", 0); 
f.setArguments(args); 

А потом в OnCreate() или onCreateView метод фрагмента, получаем аргумент.

getArguments().getInt("someNum"); 

В вашем случае это был бы предметный или сериализуемый объект.

+0

Вопрос только о Activity, а не об фрагменте –

Смежные вопросы