当我从导航抽屉中单击某个项目时,它会将字符串传递给MainActivity,然后ListView适配器会刷新。但我不知道该怎么做
没有每次调用startActivity(new Intent(getActivity(),MAinActivity.class))
主要活动
public class MainActivity extends ActionBarActivity implements ResultCallBack {
Toolbar toolbar;
recyclerAdapter adap;
PlaceHolderFragment taskFragment;
ListView listView;
urlGiver getUrlGiver;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//forceShowActionBarOverflowMenu();
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavDrawerFragment drawerFragment = (NavDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.frg_nav_drawer);
drawerFragment.setUp(R.id.frg_nav_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
listView = (ListView) findViewById(R.id.list);
if (savedInstanceState == null) {
taskFragment = new PlaceHolderFragment();
getSupportFragmentManager().beginTransaction().add(taskFragment, "fragment").commit();
} else {
taskFragment = (PlaceHolderFragment) getSupportFragmentManager().findFragmentByTag("fragment");
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
message = bundle.getString("message");
} else {
message = "http://kwtoffers.com/?feed=rss2";
}
taskFragment.startTask(message);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this, "ok clicked settings", Toast.LENGTH_SHORT).show();
}
if (id == R.id.navigate) {
startActivity(new Intent(this, SubActivity.class));
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPreExecute() {
}
@Override
public void onPostExecute(ArrayList<HashMap<String, String>> result) {
try {
listView.setAdapter(new myAdapter(result, this));
// L.m("" + result);
} catch (Exception e) {
L.m("exception from post execute" + e);
}
// L.m("" + result);
}
public static class PlaceHolderFragment extends Fragment {
bbcWeather downloadTask;
ResultCallBack callBack = null;
ArrayList<HashMap<String, String>> r;
String url;
public PlaceHolderFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callBack = (ResultCallBack) activity;
if (downloadTask != null) {
downloadTask.onAttach(callBack);
}
}
@Override
public void onDetach() {
super.onDetach();
callBack = null;
if (downloadTask != null) {
downloadTask.onDetach();
}
}
public void startTask(String url) {
if (downloadTask != null) {
downloadTask.cancel(true);
} else {
downloadTask = new bbcWeather(callBack);
this.url = url;
downloadTask.url = url;
downloadTask.execute();
}
}
}
static HashMap<String, Bitmap> images = null;
public static class bbcWeather extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ResultCallBack callBack = null;
public String url;
urlGiver urlgiver;
public bbcWeather(ResultCallBack callBack) {
this.callBack = callBack;
}
public void onAttach(ResultCallBack callBack) {
this.callBack = callBack;
}
public void onDetach() {
callBack = null;
}
HashMap<String, String> cMap = null;
@Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
if (url == null)
url = "http://kwtoffers.com/?feed=rss2";
L.m(url + "");
ArrayList<HashMap<String, String>> result = null;
try {
URL javURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) javURL.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
result = new ArrayList<>();
result = processXML(inputStream, url);
} catch (Exception e) {
L.m("exception from http url -> " + e);
}
return result;
}
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> hashMaps) {
if (callBack != null) {
callBack.onPostExecute(hashMaps);
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (callBack != null) {
callBack.onPreExecute();
}
}
public ArrayList<HashMap<String, String>> processXML(InputStream inputStream, String url) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document xmlDocument = documentBuilder.parse(inputStream);
Element rootElement = xmlDocument.getDocumentElement();
NodeList itemList = rootElement.getElementsByTagName("item");
Node currentItem = null;
NodeList itemChildren = null;
Node childItem = null;
ArrayList<HashMap<String, String>> results = new ArrayList<>();
HashMap<String, String> currentMap = null;
for (int i = 0; i < itemList.getLength(); i++) {
currentItem = itemList.item(i);
itemChildren = currentItem.getChildNodes();
currentMap = new HashMap<>();
cMap = new HashMap<>();
for (int j = 0; j < itemChildren.getLength(); j++) {
childItem = itemChildren.item(j);
if (childItem.getNodeName().equalsIgnoreCase("title")) {
//L.m("" + childItem.getTextContent());
currentMap.put("title", childItem.getTextContent());
}
if (childItem.getNodeName().equalsIgnoreCase("pubDate")) {
//L.m("" + childItem.getTextContent());
currentMap.put("pubDate", childItem.getTextContent());
}
if (childItem.getNodeName().equalsIgnoreCase("dc:creator")) {
//L.m("" + childItem.getTextContent());
currentMap.put("dc:creator", childItem.getTextContent());
}
if (childItem.getNodeName().equalsIgnoreCase("description")) {
String str = childItem.getTextContent();
str += "\n";
if (url.equals("http://open.live.bbc.co.uk/weather/feeds/en/285787/3dayforecast.rss")) {
str = " " + str.replace(",", "\n\n");
currentMap.put("description", str);
} else {
currentMap.put("description", str);
}
}
if (childItem.getNodeName().equalsIgnoreCase("link")) {
currentMap.put("description_link", childItem.getTextContent());
}
if (childItem.getNodeName().equalsIgnoreCase("content:encoded")) {
//L.m("" + childItem.getTextContent());
String t = childItem.getTextContent();
org.jsoup.nodes.Document document = Jsoup.parse(t);
String output = document.select("img").attr("src");
//String output = String.valueOf(document.getElementsByTag("img"));
L.m("" + output);
currentMap.put("imageURL", output);
}
}
results.add(currentMap);
}
return results;
}
}
}
ListView的适配器
class myAdapter extends BaseAdapter {
public static Bitmap bitmap;
public static HashMap<String, Bitmap> images;
public void setImages(HashMap<String, Bitmap> images) {
this.images = images;
}
ArrayList<HashMap<String, String>> dataSource = new ArrayList<>();
Context context;
LayoutInflater layoutInflater;
public myAdapter(ArrayList<HashMap<String, String>> dataSource, Context context) {
this.dataSource = dataSource;
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() { // to retrieve total elements in a result arraylist
return dataSource.size();
}
@Override
public Object getItem(int position) {
return dataSource.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// this will be used to add data to our custom_row.xml
View row = convertView;
Myholder holder = null;
if (row == null) {
row = layoutInflater.inflate(R.layout.custom_row, parent, false);
holder = new Myholder(row);
row.setTag(holder);
} else {
holder = (Myholder) row.getTag();
}
final HashMap<String, String> currentItem = dataSource.get(position);
holder.title.setText(currentItem.get("title"));
holder.pubdate.setText(currentItem.get("pubDate"));
holder.description.setText(currentItem.get("description"));
holder.description.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity((Activity) context, new Intent(Intent.ACTION_VIEW, Uri.parse(currentItem.get("description_link"))), Bundle.EMPTY);
}
});
holder.author.setText(currentItem.get("dc:creator"));
try {
Picasso.with(context).load(currentItem.get("imageURL")).into(holder.image);
holder.image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/external/images/media/16")));
startActivity((Activity) context, new Intent(Intent.ACTION_VIEW, Uri.parse(currentItem.get("imageURL"))), Bundle.EMPTY);
}
});
} catch (Exception e) {
L.m("" + e);
}
return row;
}
public static void setImageFromURL(Bitmap bmp) {
bitmap = bmp;
}
public Bitmap getImageFromURL() {
return bitmap;
}
}
导航抽屉片段
public class NavDrawerFragment extends Fragment implements recyclerAdapter.clicker {
RecyclerView recyclerView;
recyclerAdapter.MyViewHolder obj;
boolean t;
ActionBarDrawerToggle actionBarDrawerToggle;
private View ContainerView;
DrawerLayout drawerLayout;
private boolean learnt, fromSavedInstanceState;
public static final String PREF_FILE_NAME = "myFile", KEY_USER_LEARNT = "user_learnt";
private recyclerAdapter adap;
public NavDrawerFragment() {
// Required empty public constructor
}
public static List<information> ok() {
List<information> list = new ArrayList<>();
// int[] images = {R.mipmap.ic_action_ads,R.mipmap.ic_action_news,R.mipmap.ic_action_weather};
int[] images = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
String[] title = {"Today's Promotion", "Today's News", "3 Days Weather-forecast", "Important Contacts"};
for (int i = 0; i < 4; i++) {
information current = new information();
current.titleID = title[i];
current.ImageID = images[i];
list.add(current);
}
return list;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
learnt = Boolean.valueOf(readfromPreference(getActivity(), KEY_USER_LEARNT, "false"));
if (savedInstanceState != null) {
fromSavedInstanceState = true;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_nav_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.recycler_drawer_list);
this.drawerLayout = drawerLayout;
adap = new recyclerAdapter(getActivity(), ok());
recyclerView.setAdapter(adap);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adap.setClicker(this);
return layout;
}
public void setUp(int fragmentID, final DrawerLayout drawerLayout, Toolbar toolbar) {
ContainerView = getActivity().findViewById(R.id.frg_nav_drawer);
this.drawerLayout = drawerLayout;
actionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!learnt) {
learnt = true;
saveToPreference(getActivity(), KEY_USER_LEARNT, learnt + "true");
}
getActivity().invalidateOptionsMenu();
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if (!learnt && !fromSavedInstanceState) {
//drawerLayout.openDrawer(ContainerView);
}
this.drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
public static void saveToPreference(Context context, String PreferenceName, String PreferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PreferenceName, PreferenceValue);
editor.apply();
}
public static String readfromPreference(Context context, String PreferenceName, String DefaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return DefaultValue;
}
@Override
public void itemClicked(View v, int position) {
urlGiver setURL = new urlGiver();
String message;
Intent intent;
drawerLayout.closeDrawer(ContainerView);
switch (position) {
case 0:
message = "http://kwtoffers.com/?feed=rss2";
intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("message", message);
startActivity(intent);
getActivity().finish();
break;
case 1:
intent = new Intent(getActivity(), MainActivity.class);
message = "http://www.arabtimesonline.com/DesktopModules/DNNArticle/DNNArticleRSS.aspx?moduleid=414&tabid=69&categoryid=50";
intent.putExtra("message", message);
startActivity(intent);
getActivity().finish();
break;
case 2:
intent = new Intent(getActivity(), MainActivity.class);
message = "http://open.live.bbc.co.uk/weather/feeds/en/285787/3dayforecast.rss";
intent.putExtra("message", message);
startActivity(intent);
getActivity().finish();
break;
case 3:
intent = new Intent(getActivity(), SubActivity.class);
startActivity(intent);
break;
}
}
}