2017-10-09 48 views
0

我試圖從片段發送意圖到MainActivity。但在做startActivity(intent)在這一點上的應用程序運行良好,但每次我點擊listview片段刷新和列表視圖再次從0索引開始。從片段發送意圖的最佳方式是什麼?從片段到mainActivity的意圖

我有兩個片段和一個主要活動。所以用戶可以同時看到這兩個片段。拳頭片段是城市的列表,第二個片段是城市的描述。

非常感謝您在這件事上的時間和協助。

請檢查下面我的代碼:

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

你需要在你的活動和片段來創建一個監聽器/回調。無論何時您想要傳遞給Activity的變化,都可以通過偵聽器發送。閱讀更多信息,請致電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. 
    } 
} 
相關問題