2017-10-09 12 views
0

私はフラグメントからMainActivityにインテントを送信しようとしています。しかし、この時点でstartActivity(intent)をやっている間、アプリケーションはうまくいきますが、リストビューをクリックするたびにフラグメントがリフレッシュされ、リストビューは0から再び開始されます。フラグメントからインテントを送信する最良の方法は何ですか?フラグメントからmainActivityへの意図

私は2つの断片と1つの主な活動をしています。したがって、ユーザーは両方のフラグメントを同時に見ることができます。第1の断片は都市のリストであり、第2の断片は都市の説明である。

このたびはお時間を頂き、誠にありがとうございます。

以下の私のコードを確認してください:

public class MainActivity extends AppCompatActivity { 

    private String cityName; 

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

    fragmentManage(); 


    } 

    public void fragmentManage() { 

    CityInformationFragment cityInformationFragment = new 
    CityInformationFragment(); 
    CityList cityList = new CityList(); 


    FragmentManager fragmentManager = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = 
    fragmentManager.beginTransaction(); 

    fragmentTransaction.add(R.id.fragment2holder, cityList); 
    fragmentTransaction.add(R.id.fragment1holder, cityInformationFragment); 


    fragmentTransaction.commit(); 


    Intent intent = getIntent(); 
    cityName = intent.getStringExtra(CityList.PUT_EXTRA_KEY); 

    Bundle bundle = new Bundle(); 
    bundle.putString(CityList.PUT_EXTRA_KEY, cityName); 


    cityInformationFragment.setArguments(bundle); 


    } 

} 

をマイCityListフラグメント:

public class CityList extends Fragment implements 
    AdapterView.OnItemClickListener { 

    String[] cityList; 
    ListView listView; 
    protected static final String PUT_EXTRA_KEY = "city"; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
    container, Bundle savedInstanceState) { 
    // arrayAdapter.addAll(cityList); 

    cityList = getResources().getStringArray(R.array.cities); 

    ArrayAdapter<CharSequence> arrayAdapter = new ArrayAdapter <CharSequence>(getActivity(), android.R.layout.simple_list_item_1, cityList); 
    View view = inflater.inflate(R.layout.citylistframent, container, false); 

    listView = (ListView) view.findViewById(R.id.cityList); 
    listView.setAdapter(arrayAdapter); 
    listView.setOnItemClickListener(this); 

    return view; 
    } 


    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    TextView textView = (TextView) view; 

    String city = textView.getText().toString(); 
    Intent intent = new Intent(getActivity(), MainActivity.class); 
    intent.putExtra(PUT_EXTRA_KEY, city); 

    startActivity(intent); 
    } 
} 

マイCityInformationFragment:

public class CityInformationFragment extends Fragment { 

    String vancouver = "Vancouver, a bustling west coast seaport in British Columbia, is among Canada’s densest, most ethnically diverse cities." + 
      " A popular filming location, it’s surrounded by mountains, and also has thriving art, theatre and music scenes." + 
      " Vancouver Art Gallery is known for its works by regional artists, while the Museum of Anthropology houses preeminent First Nations collections."; 

    String calgary = "Calgary, a cosmopolitan Alberta city with numerous skyscrapers, owes its rapid growth to its status as the centre of Canada’s oil industry. However," + 
      " it’s still steeped in the western culture that earned it the nickname “Cowtown,”" + 
      " evident in the Calgary Stampede, its massive July rodeo and festival that grew out of the farming exhibitions once presented here."; 

    String kamloops = "Kamloops is a Canadian city in British Columbia, where the North and South Thompson rivers meet." + 
      " Sun Peaks Resort’s hiking trails, bike park and numerous ski runs lie to the northeast. Cougars and bears inhabit the British Columbia Wildlife Park east of town." + 
      " West, above Kamloops Lake are clay hoodoos (or spires). The riverside Secwepemc Museum & Heritage Park features the remains of a 2,000-year-old village."; 

    String toronto = "Toronto, the capital of the province of Ontario, is a major Canadian city along Lake Ontario’s northwestern shore." + 
      " It's a dynamic metropolis with a core of soaring skyscrapers, all dwarfed by the iconic, free-standing CN Tower. " + 
      "Toronto also has many green spaces, from the orderly oval of Queen’s Park to 400-acre High Park and its trails, sports facilities and zoo."; 

    String saskatoon = "Saskatoon is a city straddling the South Saskatchewan River in Saskatchewan, Canada. " + 
      "North along the riverside Meewasin Trail is Wanuskewin Heritage Park, with exhibitions exploring indigenous culture. " + 
      "On the trail’s southern stretch, native wildlife inhabit the prairie grasslands of Beaver Creek Conservation Area. " + 
      "East of the river, the Saskatoon Forestry Farm Park & Zoo has manicured gardens and a children’s zoo."; 

    TextView textView; 
    String cityName = ""; 


    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.cityinformation, container, false); 

     textView = view.findViewById(R.id.cityInformation); 

     cityName = getArguments().getString(CityList.PUT_EXTRA_KEY); 
    // Toast.makeText(getContext(), cityName, Toast.LENGTH_SHORT).show(); 
     setInformation(); 


     return view; 
    } 

    public String getVancouver() { 
     return vancouver; 
    } 

    public String getCalgary() { 
     return calgary; 
    } 

    public String getKamloops() { 
     return kamloops; 
    } 

    public String getToronto() { 
     return toronto; 
    } 

    public String getSaskatoon() { 
     return saskatoon; 
    } 

    public void setInformation() { 

     if (cityName != null) { 

      if (cityName.equals("")) { 
       textView.setText(getKamloops()); 
      } else if (cityName.equals("Calgary")) { 
       textView.setText(getCalgary()); 
      } else if (cityName.equals("Kamloops")) { 
       textView.setText(getKamloops()); 
      } else if(cityName.equals("Calgary")) { 
       textView.setText(getCalgary()); 
      } else if(cityName.equals("Saskatoon")){ 
       textView.setText(getSaskatoon()); 
      } else if(cityName.equals("Toronto")) { 
       textView.setText(getToronto()); 
      } else if(cityName.equals("Vancouver")){ 
       textView.setText(getVancouver()); 
      } 

     } else { 
      textView.setText(getKamloops()); 
     } 
    } 
} 
+1

それは何をやろうとしているように思えます他のフラグメントにデータを送信します。これを行うには、アクティビティを再度呼び出す必要はありません。実際には、同じアクティビティを起動することはお勧めできません。その代わりに、コールバック関数を作成することができます。または、好きな方は、[EventBus](https://github.com/greenrobot/EventBus)を実装し、詳細フラグメントのイベントを購読することができます。 –

答えて

0

使用することはする必要があり、それはあなたの問題を解決し、あなたはいけないeventbusコールアクティビティ、フラグメントがアクティビティ内で動作していることを理解しているドキュメントを読むe

0

インテントは、アクティビティレベルのデータ送信にのみ使用できます。フラグメント間でデータを渡すには、独自のインターフェイスを作成する必要があります。

としては、あなたがあなたの活動およびフラグメントにリスナー/コールバックを作成する必要がCommunicating with Other Fragments

0

ここで説明します。アクティビティに渡す変更があるときはいつも、リスナを介してそれを送信します。詳しくはCommunicating with Other Fragmentsをご覧ください。

まず、フラグメントのインターフェイスでリスナーを定義します。

public class CityList extends Fragment implements AdapterView.OnItemClickListener { 

    private CityListListener mListener; 

    // Host Activity must implement this listener. 
    public interface CityListListener { 
    public void onItemClicked(String city); 
    } 

    @Override 
    public void onAttach(Context context) { 
    super.onAttach(context); 

    // Makes sure that the host activity has implemented the listener 
    try { 
     mListener = (CityListListener) context; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(context.toString() 
       + " must implement CityListListener"); 
    } 
    } 

    ... 

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    TextView textView = (TextView) view; 

    String city = textView.getText().toString(); 

    // tell the host Activity about the item click. 
    mListener.onItemClicked(city); 
    } 
} 

今、あなたがあなたの活動にリスナーを実装する必要があります。

public class MainActivity extends AppCompatActivity 
    implements CityList.CityListListener { 

    ... 

    @Override 
    public void onItemClicked(String city) { 
    // This will listen to every item click in CityList Fragment 
    // Do something about the city. 
    } 
} 
関連する問題