点击活动工具栏中的添加类别图标,需要刷新片段。
我有一个Activty(ProductsAndServicesTab扩展AppCompactActivity) 在此活动中,我在工具栏上有一个按钮,用于添加类别
在此活动中,我定义了两个选项卡(Products extends Fragment and Services extends Fragment)
公共类ProductsAndServicesTab扩展了AppCompatActivity {
private TabLayout tabLayout;
private ViewPager mViewPager;
private Toolbar mToolbar;
ProgressDialog pb;
TextView show_prof_menu_title_text;
ImageView show_prof_edit_profile_icon, show_prof_logo_menu_icon;
String businessId = null;
String sessionId = null;
static DbOperations dbOperations;
static Context context;
ConnectAndGetResponseInBackground connectAndGetResponseInBackground;
static {
try {
context = abcApp.getContext();
dbOperations = new DbOperations(context);
} catch (Exception e) {
e.printStackTrace();
}
}
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products_services_details);
mToolbar = (Toolbar) findViewById(R.id.inc_tb_top);
show_prof_menu_title_text = (TextView) findViewById(R.id.show_prof_menu_title_text);
show_prof_edit_profile_icon = (ImageView) findViewById(R.id.show_prof_edit_profile_icon);
show_prof_edit_profile_icon.setImageResource(R.drawable.category);
show_prof_logo_menu_icon = (ImageView) findViewById(R.id.show_prof_logo_menu_icon);
businessId = getIntent().getExtras().getString("businessid");
sessionId = getIntent().getExtras().getString("sessionid");
dbOperations.open();
setSupportActionBar(mToolbar);
show_prof_menu_title_text.setText("Items");
final Drawable upArrow = ResourcesCompat.getDrawable(getResources(), R.drawable.abc_ic_ab_back_material, null);
upArrow.setColorFilter(ContextCompat.getColor(context, android.R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
mViewPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(mViewPager);
tabLayout = (TabLayout) findViewById(R.id.stl_tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ffffff"));
changeTabsFont();
show_prof_edit_profile_icon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addCategoryDiag();
}
});
}
private void changeTabsFont() {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/pts75f-webfont.ttf");
((TextView) tabViewChild).setTypeface(tf);
}
}
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle b = new Bundle();
b.putString("sessionId", sessionId);
b.putString("businessId", businessId);
Products products = new Products();
products.setArguments(b);
Services services = new Services();
services.setArguments(b);
adapter.addFragment(products, "Products");
adapter.addFragment(services, "Services");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
/* //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return false;
}*/
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void addCategoryDiag() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ProductsAndServicesTab.this);
final android.app.AlertDialog alertDialogMain = builder.create();
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View alertView = inflater.inflate(R.layout.custom_dialog_add_category, null);
Button custom_cancel = (Button) alertView.findViewById(R.id.custom_cancel);
Button custom_ok = (Button) alertView.findViewById(R.id.custom_ok);
final ListView lv_add_category = (ListView) alertView.findViewById(R.id.lv_add_category);
final EditText et_add_category = (EditText) alertView.findViewById(R.id.et_add_category);
final RadioGroup rg_products_services = (RadioGroup) alertView.findViewById(R.id.rg_products_services);
ArrayList<String> categoryTypes = new ArrayList<String>();
categoryTypes = dbOperations.getAllCategoryNameForBusinessAndType(businessId, "Products");
/* if (categoryTypes == null || categoryTypes.size() == 0){
categoryTypes.add("General");
}*/
if (categoryTypes != null && categoryTypes.size() > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ProductsAndServicesTab.this,
android.R.layout.simple_list_item_1, android.R.id.text1, categoryTypes);
lv_add_category.setAdapter(adapter);
} else {
lv_add_category.setAdapter(null);
}
custom_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialogMain.dismiss();
}
});
rg_products_services.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton getRb_editProf_gender = (RadioButton) radioGroup.findViewById(i);
getRb_editProf_gender.setChecked(true);
String type = getRb_editProf_gender.getText().toString();
et_add_category.setText(null);
ArrayList<String> categoryTypes = new ArrayList<String>();
categoryTypes = dbOperations.getAllCategoryNameForBusinessAndType(businessId, type);
if (categoryTypes != null && categoryTypes.size() > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ProductsAndServicesTab.this,
android.R.layout.simple_list_item_1, android.R.id.text1, categoryTypes);
lv_add_category.setAdapter(adapter);
} else {
lv_add_category.setAdapter(null);
}
}
});
custom_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!et_add_category.getText().toString().trim().equals("")) {
final String categoryText = et_add_category.getText().toString();
String categoryTypeStr = null;
if (rg_products_services.getCheckedRadioButtonId() != -1) {
RadioButton getRb_editProf_gender = (RadioButton) rg_products_services.findViewById(rg_products_services.getCheckedRadioButtonId());
categoryTypeStr = getRb_editProf_gender.getText().toString();
}
boolean doesCategoryExists = dbOperations.checkCategoryExists(businessId, categoryText, categoryTypeStr);
if (!doesCategoryExists) {
if (Utility.isNetworkConnected(ProductsAndServicesTab.this)) {
// Toast.makeText(ProductsAndServicesTab.this, "I m clicked " + categoryTypeStr + " * " + categoryText, Toast.LENGTH_LONG).show();
int category_type = -1;
if (categoryTypeStr != null && categoryTypeStr.equals("Products"))
category_type = 0;
if (categoryTypeStr != null && categoryTypeStr.equals("Services"))
category_type = 1;
pb = new ProgressDialog(ProductsAndServicesTab.this);
pb.setMessage("In Progress....Please Wait");
pb.setCancelable(false);
pb.show();
String addCategoryJsonReqStr = FormJson.formAddingCategoryJsonStr(businessId, sessionId, category_type, categoryText);
final String finalCategoryTypeStr = categoryTypeStr;
connectAndGetResponseInBackground = new ConnectAndGetResponseInBackground() {
@Override
public void onResponseReceived(String result) {
pb.dismiss();
System.out.println("AddCategory req :" + result);
String addedCategoryResponse = ProcessResponse.processAddedCategoryResponse(businessId, finalCategoryTypeStr, categoryText, result);
if (addedCategoryResponse != null) {
if (addedCategoryResponse.equals("Success")) {
Toast.makeText(ProductsAndServicesTab.this, categoryText + " added to " + finalCategoryTypeStr + " category successfully..", Toast.LENGTH_SHORT).show();
alertDialogMain.dismiss();
} else {
Utility.showDialog("Error", addedCategoryResponse, ProductsAndServicesTab.this);
}
} else {
Utility.showDialog("Error", "Unexpected error.Please try again later.", ProductsAndServicesTab.this);
}
}
};
connectAndGetResponseInBackground.setJson(addCategoryJsonReqStr);
connectAndGetResponseInBackground.execute(URLs.PRODUCTS_SERVICES);
System.out.println("AddCategory req :" + URLs.PRODUCTS_SERVICES + addCategoryJsonReqStr);
} else {
Toast.makeText(ProductsAndServicesTab.this, "No Internet Connection, please try again..!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ProductsAndServicesTab.this, "Category already exists.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ProductsAndServicesTab.this, "Please enter category.", Toast.LENGTH_LONG).show();
}
}
});
alertDialogMain.setView(alertView);
alertDialogMain.show();
alertDialogMain.setCancelable(false);
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
产品片段(服务片段的相同代码):
public class Products extends Fragment实现了View.OnClickListener {
AppPreferences appPreferences;
AppCompatSpinner spinr_products_services;
ListView lv_products_services;
SwipeRefreshLayout swiperefresh_products_services;
FloatingActionButton fab_products_services_add_items;
String businessId = null;
String sessionId = null;
boolean isImageSet = false;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Bitmap selectedImageBitmap;
ImageView iv_item;
ArrayList<String> categoryTypes = new ArrayList<String>();
ArrayList<CategoryItems_Table> categoryItemsList;
Menu contextualMenu;
ProgressDialog pb;
ProductsAndServicesAdapter productsAndServicesAdapter;
private static DbOperations dbOperations;
static Context context;
static {
try {
context = abcApp.getContext();
dbOperations = new DbOperations(context);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_products, container, false);
dbOperations.open();
appPreferences = new AppPreferences(getActivity());
swiperefresh_products_services = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh_products_services);
lv_products_services = (ListView) rootView.findViewById(R.id.lv_products_services);
spinr_products_services = (AppCompatSpinner) rootView.findViewById(R.id.spinr_products_services);
fab_products_services_add_items = (FloatingActionButton) rootView.findViewById(R.id.fab_products_services_add_items);
businessId = getArguments().getString("businessId");
sessionId = getArguments().getString("sessionId");
fab_products_services_add_items.setOnClickListener(this);
getAndSetData(null);
swiperefresh_products_services.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getAndSetData(spinr_products_services.getSelectedItem().toString());
}
});
return rootView;
}
public void getAndSetData(String currentCategoryName) {
categoryTypes = dbOperations.getAllCategoryNameForBusinessAndType(businessId, "Products");
if (categoryTypes != null && categoryTypes.size() > 0) {
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, categoryTypes);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinr_products_services.setAdapter(dataAdapter);
if (currentCategoryName != null) {
int position = ((ArrayAdapter) spinr_products_services.getAdapter()).getPosition(currentCategoryName);
spinr_products_services.setSelection(position);
}
}
spinr_products_services.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String categoryName = adapterView.getItemAtPosition(i).toString();
System.out.println("Products spinnerSelectCategory: " + categoryName);
categoryItemsList = dbOperations.getAllItemsForTypeBusinessAndCategoryName(businessId, categoryName, "Products");
if (categoryItemsList != null && categoryItemsList.size() > 0) {
productsAndServicesAdapter = new ProductsAndServicesAdapter(getActivity(), categoryItemsList, "general", sessionId);
lv_products_services.setAdapter(productsAndServicesAdapter);
} else {
lv_products_services.setAdapter(null);
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
if (swiperefresh_products_services.isRefreshing()) {
swiperefresh_products_services.setRefreshing(false);
}
}
按下工具栏按钮添加类别后,我添加了一个类别,新添加的类别未显示在片段的微调元素中。Activity's toolbar name is items and right side is add category imageButton
答案 0 :(得分:0)
我建议使用这个界面。创建一个管理器类(单例),每个使用类别的视图都必须实现该接口。然后在管理器上注册已实现的视图。您必须通过manager.getInstance().add(mycategory);
添加类别。在添加内部,您可以调用notifyCallbacks();
我已经在我的应用中实现了这个逻辑。 检查此链接上的代码:
Unable to refresh listview data within same fragments used under different tabs
答案 1 :(得分:0)
要更新片段,您需要使用回调将数据从活动发送到片段。然后更新片段中收到的数据。分享活动和片段的代码,我将提供完整的解决方案。