繁体   English   中英

Android:从活动到其他片段选项卡的界面不起作用

[英]Android: Interface from activity to other fragment tabs not working

我的应用程序中有3个标签,并且通过Interface通过MainActivity的提示(称为“浮动操作按钮”)更新每个标签。 根据显示的选项卡,提示会有所不同。

我要在提示中单击“确定”后立即更新当前显示的选项卡,但是正在发生的情况是只有第一个选项卡中的界面正在工作,因此只有选项卡1得到更新。

当我单击第二个选项卡并从MainActivity的FAB调用提示时,单击第二个选项卡的提示中的“确定”后,第二个选项卡不会更新,尽管在显示第一个选项卡时可以使用。

我怎样才能解决这个问题? 请帮忙。

这是我的代码:

MainActivity FAB:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.floatingActionButton_main2);
fab.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    int position = tabLayout.getSelectedTabPosition();

    switch (position) {
      case 0:

        // first tab is selected

        AddBudget_Main(); //refresh fragment contents
        break;
      case 1:
        // second tab is selected

        /* DOES NOT WORK - 2nd TAB NOT BEING UPDATED*/
        addFund_Prompt_Main(); //refresh fragment contents 

        break;
      case 2:
        // third tab is selected

        break;

    }

MainActivity界面:

public void setPopupListener(PopupListener popupListener) {
  this.popupListener = popupListener;
}

public interface PopupListener {
  void onDialogClick(String value); //String value
}

片段标签:

@Override
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
  super.onViewCreated(view, savedInstanceState);
  ((Main2Activity) getActivity()).setPopupListener(new Main2Activity.PopupListener() {
    @Override
    public void onDialogClick(String value) {

      Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
      if (value == "settings_tab") {  //settings_tab =  2nd fragment. (different content of value variable according to the fragment)
        viewFunds(view); //refresh fragment  display
      }
    }
  });
}

addFund_Prompt_Main:

public void addFund_Prompt_Main() {
  int cnt;
  Cursor res = myDb.getConfigData();
  cnt = res.getCount();

  if (cnt == 40) {
    Toast.makeText(context, "Fund limit of 40 already reached, " +
      "delete some funds to be able to enter new items", Toast.LENGTH_LONG).show();
  } else {
    //code 2
    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(context);
    View promptsView = li.inflate(R.layout.prompts, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
      context);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView
      .findViewById(R.id.editTextDialogUserInput);
    final NumberPicker newPercentage = (NumberPicker) promptsView
      .findViewById(R.id.AddPercentage);

    newPercentage.setMinValue(0);
    newPercentage.setMaxValue(100);

    // set dialog message
    alertDialogBuilder
      .setCancelable(false)
      .setPositiveButton("OK",
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            // get user input and set it to result
            // edit text
            //result.setText(userInput.getText());

            //write to database
            String getInput;
            getInput = userInput.getText().toString();
            getInput = userInput.getText().toString().trim();
            if (getInput.matches(" ")) {
              Toast.makeText(context, "Cannot create empty fund name", Toast.LENGTH_LONG).show();
            } else if (getInput.matches("")) {
              Toast.makeText(context, "Cannot create empty fund name", Toast.LENGTH_LONG).show();
            } else {
              //int cntInserted;
              //cntInserted=0;
              boolean isInserted = myDb.insertFund(userInput.getText().toString().trim(), String.valueOf(newPercentage.getValue()));
              if (isInserted == true) {
                Toast.makeText(context, "Fund successfully added", Toast.LENGTH_LONG).show();
              } else {
                Toast.makeText(context, "ERROR: Fund not added", Toast.LENGTH_LONG).show();
              }

              popupListener.onDialogClick("settings_tab");

              //viewFunds(rootview);
              //create dynamic edittext to mainactivity
            }

          }
        })
      .setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
          }
        });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
  }


}

viewFunds:

public View viewFunds(final View rootview) { //display funds dynamically in config layout | L
  Cursor res2 = myDb.getConfigData();
  res2.moveToFirst();
  //showMessage("Number of rows",Integer.toString(res2.getCount()));

  LinearLayout linearLayout = (LinearLayout) rootview.findViewById(R.id.ll_config);

  linearLayout.removeAllViews(); //clear layout first - LINE WITH ISSUE
  linearLayout.setGravity(Gravity.CENTER);

  LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  LinearLayout.LayoutParams lp3 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

  //create dynamic objects inside scrollview and dynamic linear layout - horizontal
  for (int i = 0; i < res2.getCount(); i++) {
    LinearLayout llh = new LinearLayout(getActivity());
    llh.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams lp_llh = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    llh.setLayoutParams(lp_llh);
    llh.setBackgroundColor(Color.parseColor("#12ba15"));


    linearLayout.addView(llh);

    NumberPicker numberPicker = new NumberPicker(getActivity());
    numberPicker.setMinValue(0);
    numberPicker.setMaxValue(100);
    LinearLayout.LayoutParams lp_np = new LinearLayout.LayoutParams(70, LinearLayout.LayoutParams.WRAP_CONTENT);
    numberPicker.setLayoutParams(lp_np);
    numberPicker.setGravity(Gravity.CENTER_VERTICAL);

    //showMessage("value",res2.getString(3));
    numberPicker.setValue(Integer.parseInt(res2.getString(2))); //
    TextView textView = new TextView(getActivity());
    textView.setText(res2.getString(1));


    llh.addView(textView);
    linearLayout.addView(numberPicker);

    //create dynamic button
    final Button buttonD = new Button(getActivity());
    final Button buttonD2 = new Button(getActivity());
    buttonD.setLayoutParams(lp2);
    buttonD.setText("-");
    buttonD.setId(Integer.valueOf(res2.getString(0))); //get id from id of corresponding fund row

    buttonD2.setLayoutParams(lp3);
    buttonD2.setText("Edit");
    buttonD2.setId(Integer.valueOf(res2.getString(0)) + 100); //add 100 to separate id of edit from delete button


    ids[i] = Integer.valueOf(res2.getString(0)); //get ids and store to array
    buttonD.setOnClickListener(
      new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          //showMessage("button id", Integer.toString(buttonD.getId()));

          // get prompts.xml view
          LayoutInflater li = LayoutInflater.from(getActivity());
          View promptsView = li.inflate(R.layout.confirm_delete_prompt, null); //assign to layout

          AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            getActivity());

          // set prompts.xml to alertdialog builder
          alertDialogBuilder.setView(promptsView);

          /*final EditText userInput = (EditText) promptsView
                  .findViewById(R.id.editTextDialogUserInput);*/

          // set dialog message
          alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("OK",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {


                  boolean isDelete = myDb.deleteData(String.valueOf(buttonD.getId()));

                  if (isDelete == true) {
                    Toast.makeText(getActivity(), "Fund Deleted", Toast.LENGTH_LONG).show();

                    viewFunds(rootview);
                  } else {
                    Toast.makeText(getActivity(), "Fund Not Deleted", Toast.LENGTH_LONG).show();
                  }
                  //create dynamic edittext to mainactivity
                }
              })
            .setNegativeButton("Cancel",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                  dialog.cancel();
                }
              });

          // create alert dialog
          AlertDialog alertDialog = alertDialogBuilder.create();

          // show it
          alertDialog.show();

          //deleteData();
          //Cursor res = myDb.getConfigData();
          //cnt=res.getCount();

        }
      }
    );
    //edit button
    buttonD2.setOnClickListener(
      new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          int x;
          x = buttonD2.getId() - 100;
          //showMessage("button id",String.valueOf(x));
          Cursor res3 = myDb.getFundName(x);
          res3.moveToFirst();

          //showMessage("btn id",String.valueOf(buttonD2.getId()));
          // get prompts.xml view
          LayoutInflater li = LayoutInflater.from(getActivity());
          View promptsView = li.inflate(R.layout.update_fund_details, null);

          AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            getActivity());

          // set prompts.xml to alertdialog builder
          alertDialogBuilder.setView(promptsView);

          final EditText userInput = (EditText) promptsView
            .findViewById(R.id.editText_Fundname);
          final NumberPicker newPct = (NumberPicker) promptsView
            .findViewById(R.id.numberPicker_editPct);

          //FundName=res3.getF
          userInput.setText(res3.getString(1));
          newPct.setMinValue(0);
          newPct.setMaxValue(100);
          newPct.setValue(Integer.valueOf(res3.getString(2)));

          // set dialog message
          alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("OK",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                  // get user input and set it to result

                  //write to database
                  String getInput, getInput2;
                  getInput = userInput.getText().toString().trim();
                  getInput2 = String.valueOf(newPct.getValue());

                  if (getInput.matches(" ")) {
                    Toast.makeText(getActivity(), "Cannot create empty fund name", Toast.LENGTH_LONG).show();
                  } else if (getInput.matches("")) {
                    Toast.makeText(getActivity(), "Cannot create empty fund name", Toast.LENGTH_LONG).show();
                  } else if (Double.compare(Double.valueOf(getInput2), 0) == 0) {
                    Toast.makeText(getActivity(), "Cannot create scheduled expense with no amount", Toast.LENGTH_LONG).show();
                  } else {
                    if (CheckTotalPercentage(Integer.valueOf(getInput2), String.valueOf(buttonD2.getId()))) {
                      Toast.makeText(getActivity(), "Total savings funds should not exceed 90% of income", Toast.LENGTH_LONG).show();
                    } else {
                      boolean isUpdated = myDb.updateConfigName(buttonD2.getId() - 100, String.valueOf(userInput.getText()), String.valueOf(newPct.getValue()));
                      if (isUpdated == true)
                        Toast.makeText(getActivity(), "Data Updated", Toast.LENGTH_LONG).show();
                      else
                        Toast.makeText(getActivity(), "Data not Updated", Toast.LENGTH_LONG).show();

                      viewFunds(rootview);
                    }

                  }

                  //create dynamic edittext to mainactivity


                }
              })
            .setNegativeButton("Cancel",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                  dialog.cancel();
                }
              });

          // create alert dialog
          AlertDialog alertDialog = alertDialogBuilder.create();

          // show it
          alertDialog.show();
        }
      }
    );


    llh.addView(buttonD); //delete
    llh.addView(buttonD2); //edit
    //linearLayoutD.addView(button);

    res2.moveToNext();
  }

  //return scrollView;
  return rootview;

}

viewFunds的显示示例:

========================================

基金1 [编辑按钮] [删除按钮]

数量:100

基金2 [编辑按钮] [删除按钮]

数量:200

基金3 [编辑按钮] [删除按钮]

数量:300

========================================

您的这段代码未获得正确的制表符位置...因此总是给0位置,这就是为什么每次仅执行第一种情况int position = tabLayout.getSelectedTabPosition();

使用OnTabSelectedListener ....即

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
@Override
    public void onTabSelected(TabLayout.Tab tab){
        int position = tab.getPosition();
}
});

使用上面的代码,您将获得正确的接线片位置...。然后,开关盒将处于适当的大小写,您将获得正确的结果...

在您的活动中

全局创建片段引用。

FirstFragment firstFragment;
SecondFragment secondFragment;
ThirdFragment thirdFragment;

然后在onCreate中

firstFragment=new FirstFragment();
secondFragment=new SecondFragment();
thirdFragment=new ThirdFragment();

然后,在每个片段类(它们全部三个)中添加此方法。

public void dataUpdated(String newData){
    //Update UI with newData
}

AddBudget_Main() ,当有新数据可用时,调用firstFragment.dataUpdated(updated_data);

addFund_Prompt_Main()调用addFund_Prompt_Main() secondFragment.dataUpdated(updated_data); 对第三个片段执行相同的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM