从android eclipse中的片段刷新或更新listadapter
Posted
技术标签:
【中文标题】从android eclipse中的片段刷新或更新listadapter【英文标题】:Refresh or Update the listadapter from a fragment in android eclipse 【发布时间】:2016-03-11 05:47:15 【问题描述】:单击侧导航菜单时,我有一个包含一些片段的 MainActivity 运行。在侧面导航菜单中有一个项目 Called Number of SMS 应在您选择所需电话号码的其他片段中立即更新。但问题是我不知道如何从该片段刷新列表适配器。我定义了一个名为 allvalues 的类,其中包含我所有的全局变量。负责短信计数的变量是 allvalues.NumberOfLocations 这是MainActivity的代码:
package com.faraz.locatecar;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity
private DrawerLayout mDrawerLayout;
public static ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
public static ArrayList<NavDrawerItem> navDrawerItems;
public static NavDrawerListAdapter adapter;
String passString;
ProgressDialog mProgressDialog;
MyDb dbf;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allvalues.context = this;
if(!allvalues.setno)
Toast.makeText(allvalues.context, "Please choose a number", Toast.LENGTH_SHORT).show();
dbf = new MyDb(allvalues.context);
String phoneNumbers = dbf.trakersCount();
// to check if there is any phone numbers or not
if(phoneNumbers.matches("0"))
Toast.makeText(allvalues.context, "Please save a number first", Toast.LENGTH_SHORT).show();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1), true, allvalues.NumberOfLocations));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Traker number choose
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, phoneNumbers));
// add tracker number
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
)
public void onDrawerClosed(View view)
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
public void onDrawerOpened(View drawerView)
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
;
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null)
// on first time display view for first nav item
displayView(0);
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
// display view for selected nav drawer item
displayView(position);
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position)
// update the main content by replacing fragments
Fragment fragment = null;
switch (position)
case 0:
fragment = new HomeFragment();
break;
case 1:
new SmsBased().execute();
break;
case 2:
fragment = new OldListReader();
break;
case 3:
fragment = new ShowEveryThing();
break;
case 4:
break;
case 5:
fragment = new ChoosePhoneNumber();
break;
case 6:
fragment = new NewTrakerRegister();
break;
default:
break;
if (fragment != null)
final String MyPref = "mypref";
SharedPreferences prefs = getSharedPreferences(MyPref, 0);
if(prefs.getBoolean("FirstRun", true))
prefs.edit().putBoolean("FirstRun", false).commit();
fragment = new PasswordFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
passString = allvalues.pass;
else
passString = dbf.passString();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
else
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
@Override
public void setTitle(CharSequence title)
mTitle = title;
getActionBar().setTitle(mTitle);
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState)
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
@Override
public void onConfigurationChanged(Configuration newConfig)
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
// Async part
private class SmsBased extends AsyncTask<Void, Void, Void>
@Override
protected void onPreExecute()
super.onPreExecute();
mProgressDialog = new ProgressDialog(allvalues.context);
mProgressDialog.setTitle("Please wait ");
mProgressDialog.setMessage("SMS sending is in progress");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
@Override
protected Void doInBackground(Void... params)
allvalues.send_command = SmsManager.getDefault();
String SendChangedPassword = "where," + passString + "#";
allvalues.send_command.sendTextMessage(allvalues.PhoneNumberToSend, null, SendChangedPassword, null, null);
return null;
@Override
protected void onPostExecute(Void result)
// Set title into TextView
Toast.makeText(allvalues.context, "SMS sent", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
这是另一个片段,在这个片段中,已经用户保存的电话号码将显示在一个列表中,单击该号码,首先将选择该号码,然后应该是 allvalues.NumberOfLocations已更新,等于所选数量的已接收消息数。
package com.faraz.locatecar;
import java.util.ArrayList;
import android.app.Fragment;
import android.app.FragmentManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ChoosePhoneNumber extends Fragment
private static int i;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View view = inflater.inflate(R.layout.choose_number, container, false);
allvalues.AllPhones_list = new ArrayList<String>();
MyDb phonechoose = new MyDb(allvalues.context);
phonechoose.readTrakers();
allvalues.showphones = (ListView) view.findViewById(R.id.listphone);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(allvalues.context,android.R.layout.simple_list_item_1, android.R.id.text1, allvalues.AllPhones_list);
allvalues.showphones.setAdapter(adapter);
// just added from here
allvalues.showphones.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id)
final String item = (String) parent.getItemAtPosition(position);
allvalues.PhoneNumberToSend = item;
Toast.makeText(allvalues.context, "شماره :" + allvalues.PhoneNumberToSend, Toast.LENGTH_SHORT).show();
allvalues.setno = true;
SMSNumbers();
Fragment fr = new HomeFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, fr).commit();
);
// till up here
return view;
public void SMSNumbers()
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = allvalues.context.getContentResolver().query(uriSms, new String[]"_id", "address", "date", "body",null,null,null);
if(cursor!=null)
cursor.moveToFirst();
while (cursor.moveToNext())
String address = cursor.getString(1);
if(address.equals(allvalues.PhoneNumberToSend))
i++;
allvalues.NumberOfLocations = i + "";
Toast.makeText(allvalues.context, allvalues.NumberOfLocations, Toast.LENGTH_SHORT).show();
但是导航抽屉里面的数字没有更新... 我还尝试在该行之后调用导航适配器: allvalues.NumberOfLocations = i + ""; 但它没有用...... 请帮帮我...
【问题讨论】:
【参考方案1】:我建议像这样在您的片段中创建一个自定义侦听器:
public interface FragmentListener
void refreshData();
并在您的片段中为此侦听器声明一个变量:
private FragmentListener listener;
在你的 onItemClickListener 中:
listener.refreshData();
现在在你的片段中创建一个方法来设置这个监听器:
public void setListener(FragmentListener listener)
this.listener = listener;
最后在您创建片段时的活动中:
ChoosePhoneNumber fragment = new Fragment();
fragment.setListener(new FragmentListener()
public void refreshData()
//Whatever you want to do.
);
【讨论】:
我听从了你的建议,在我创建片段的 MainActivity 中遇到了这个错误消息:fragment = new ChoosePhoneNumber(); fragment.setListener(new FragmentListener() public void refreshData() );我收到此错误:方法 setListener(new ChoosePhoneNumber.FragmentListener()) 未为 Fragment 类型定义【参考方案2】:我通过在片段末尾添加这两行,从 ChoosePhoneNumber 片段中再次刷新 MainActivity(重新加载),从而实现了目标:
getActivity().finish();
getActivity().startActivity(getActivity().getIntent());
【讨论】:
以上是关于从android eclipse中的片段刷新或更新listadapter的主要内容,如果未能解决你的问题,请参考以下文章
ViewPager 未从代码、android、eclipse 更新
无法从 ViewPager 中的另一个片段刷新/更新片段中的列表视图