从fragment到mainActivity的意图

时间:2017-10-09 21:44:38

标签: java android

我试图将片段中的意图发送到MainActivity。但是在此时进行startActivity(intent)应用程序运行良好,但每次点击listview片段时都会刷新,listview会再次从0索引开始。从片段发送意图的最佳方法是什么?

我有两个片段和一个主要活动。因此用户可以同时看到两个片段。拳头片段是城市列表,第二个片段是城市的描述。

非常感谢您在这件事上的时间和帮助。

请检查下面的代码:

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());
        }
    }
}

3 个答案:

答案 0 :(得分:0)

使用eventbus它将解决您的问题,您不需要调用活动,片段正在活动内阅读文档您理解我

答案 1 :(得分:0)

Intent仅可用于在Activity级别发送数据。要在片段之间传递数据,我们需要创建自己的接口。

如此处所述[{3}}

答案 2 :(得分:0)

您需要在Activity和Fragment中创建一个监听器/回调。每当您想要传递给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);
  }
}

现在,您需要在Activity中实现侦听器:

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.
  }
}