2017-01-11 1 views
0

액티비티의 툴바에있는 카테고리 추가 아이콘 클릭시 조각을 새로 고침해야합니다.액티비티의 액션 클릭시 조각 새로 고침

가 나는 두 개의 탭 정의이 작업에서는 카테고리

을 추가하기 위해 내가 도구 모음에 버튼이이 활동에 Activty (ProductsAndServicesTab이 AppCompactActivity를 확장) 이

(제품 것은 확장 조각 및 서비스 조각을 확장)

공용 클래스는 ProductsAndServicesTab는 {

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


} 

}

AppCompatActivity를 확장 0

제품 조각 (서비스 조각에 대한 동일 코드) :

공용 클래스 제품은 내가 카테고리를 추가하기위한 도구 모음 단추를 누른 후 조각이 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

이 인터페이스를 권하고 싶습니다. 관리자 클래스 (싱글 톤)를 만들고 카테고리를 사용하는 모든 뷰는 인터페이스를 구현해야합니다. 그런 다음 구현 된 뷰를 관리자에 등록하십시오. manager.getInstance().add(mycategory);을 통해 카테고리를 추가해야합니다. 추가 문의 내용 notifyCallbacks();

저는 이미이 논리를 내 응용 프로그램에 구현했습니다. 이 링크를 내 코드를 확인 :

Unable to refresh listview data within same fragments used under different tabs

0

당신이 조각에 활동에서 데이터를 전송하는 콜백을 사용하는 데 필요한 조각을 업데이트합니다. 그런 다음 조각에서받은 데이터를 업데이트하십시오. 활동 및 조각에 대한 코드를 공유하고, 나는 완전한 해결책을 제공 할 것이다.

+0

위 질문에서 내 코드를 업데이트하십시오. –

관련 문제