简体   繁体   English

将按钮名称从 MainActivity 发送到 Fragment

[英]Send Button Name From MainActivity to Fragment

I'm new in Android Studio JAVA development and this is my first project and expérience with both JAVA and android studio.我是 Android Studio JAVA 开发的新手,这是我的第一个项目和对 JAVA 和 ZC31B320364CE7EC951B32036662FFZ 开发的第一个项目和经验。 My problem is that I'm trying to send the Button Name by double-clicked from the Main Activity called BardoMap to a Tab fragment ( to specific Fragment called EnglishBardoFragment ) so I can use the Name button to call some data from the FireBase.我的问题是我试图通过从名为BardoMap的主 Activity 双击将按钮名称发送到选项卡片段(到名为EnglishBardoFragment的特定片段),因此我可以使用名称按钮从 FireBase 调用一些数据。 I tried to use Bundle at all but I couldn't find the right solution to only send the button name to the Fragment I manage to do all the rest of the work can anyone please help me with some idea or information about how to that value from the activity to the specific fragment我完全尝试使用 Bundle,但我找不到正确的解决方案,只将按钮名称发送到我设法完成所有 rest 工作的片段,任何人都可以帮助我提供一些关于如何实现该值的想法或信息从活动到特定片段

this is the code of the MainActivity BardoMap这是 MainActivity BardoMap的代码

public class BardoMap extends AppCompatActivity   {
     private Button AddBardobtn;
     private Button BackB;
     private Button SavePositionB;
     private ViewGroup rootLayout;
     private int _xDelta;
     private int _yDelta;
     private int X ;
     private int Y ;

    RelativeLayout relativeLayout;
    DatabaseReference savig;
    Button   button1;
    int i = 0 ;
    int j  ;

    public String NameButton;
     private    long startTime ;
    private  int clickCount;
    private long duration ;
    static final int MAX_DURATION = 500;
    List<Button> Listbuttons = new ArrayList<Button>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_bardo_map);
        Bundle bundle = new Bundle();
        bundle.putInt("SIDE",2);

        savig = FirebaseDatabase.getInstance().getReference();

        rootLayout = findViewById(R.id.view_root);
        SavePositionB = findViewById(R.id.SavePositionB);


        relativeLayout = findViewById(R.id.view_root);
         FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction t = manager.beginTransaction();
        EnglishBardoFragment engB = new EnglishBardoFragment();

       DatabaseReference usersRef = savig.child("Positions");
       usersRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
               if ( snapshot.exists())
                {

                    for (DataSnapshot snapshot1 : snapshot.getChildren())
                    {
                          i++;
                           String uid = snapshot1.getKey();
                           BeaconsPosition _Position = new BeaconsPosition();
                           button1 = new Button(BardoMap.this);

                        button1.setId(i);
                        button1.setText(uid);

                        _Position.setXPosition(snapshot1.child("xposition").getValue().toString());
                        _Position.setYPosition(snapshot1.child("yposition").getValue().toString());
                        float x=Float.parseFloat( _Position.getXPosition());
                        float y=Float.parseFloat( _Position.getYPosition());
                        button1.setX(x);
                        button1.setY(y);
                        button1.setTag("DragingObject");
                        Listbuttons.add(button1);
                        button1.setLayoutParams(new
                                RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT));

                         if (relativeLayout != null){
                            relativeLayout.addView(button1);


                             button1 = ((Button) findViewById(i));


                             button1.setOnTouchListener(new View.OnTouchListener() {
                                 @Override
                                 public boolean onTouch(View v, MotionEvent event) {
                                     int X = (int) event.getRawX();
                                     int Y = (int) event.getRawY();
                                     switch (event.getAction() & MotionEvent.ACTION_MASK)
                                     {
                                         case MotionEvent.ACTION_DOWN:
                                             RelativeLayout.LayoutParams lParms = (RelativeLayout.LayoutParams) v.getLayoutParams();
                                             _xDelta = X - lParms.leftMargin;
                                             _yDelta = Y - lParms.topMargin;
                                             startTime = System.currentTimeMillis();

                                             clickCount++;
                                             break;
                                         case  MotionEvent.ACTION_UP:
                                             long time = System.currentTimeMillis() - startTime;
                                             duration = duration + time;
                                             if(clickCount == 2)
                                             {
                                                 if(duration<= MAX_DURATION)
                                                 {
                                                     NameButton = ((Button) v).getText().toString();
                                                     Toast.makeText(BardoMap.this, "double tap " + NameButton,Toast.LENGTH_LONG).show();

                                                     OpenBardoInsertDataByID();
                                                 }
                                                 clickCount = 0;
                                                 duration = 0;
                                                 break;
                                             }
                                         case MotionEvent.ACTION_POINTER_DOWN:
                                             break;
                                         case MotionEvent.ACTION_POINTER_UP:
                                             break;
                                         case MotionEvent.ACTION_MOVE:
                                             RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v .getLayoutParams();
                                             layoutParams.leftMargin = X - _xDelta;
                                             layoutParams.topMargin = Y - _yDelta;
                                             layoutParams.rightMargin = -250;
                                             layoutParams.bottomMargin = -250;
                                             v.setLayoutParams(layoutParams);
                                             break;
                                     }
                                     rootLayout.invalidate();

                                     return true;
                                 }


                             });
                        }


                    }

                }


            }

          @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }



        });

        AddBardobtn = findViewById(R.id.AddBeaconB);
        BackB = findViewById(R.id.BackB);
        SavePositionB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              SaveButtonPosition();
            }
        });
        AddBardobtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    OpenBardoInsertData();

            }
        });
        BackB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  MainMenu();
            }
        });
    }

   private void SaveButtonPosition() {
       for(Button b:Listbuttons) {

                X = (int) b.getX();
                Y = (int) b.getY();
                BeaconsPosition beaconsposition = new BeaconsPosition( String.valueOf(X) ,String.valueOf(Y)  );
                savig.child("Positions").child(b.getText().toString()).setValue(beaconsposition);
                savig.child("0").child("Musees").child("Bardo").child("Beacons").child(b.getText().toString()).child("Position").setValue(beaconsposition);

               Toast.makeText(this, "very good souleima " +Listbuttons.size() , Toast.LENGTH_SHORT).show();

       }

    }

    private void MainMenu() {
        Intent intent = new Intent(this , MainActivity.class);
        startActivity(intent);
    }

    private void OpenBardoInsertData() {
    Intent intent = new Intent(this , BardoTab.class);
       startActivity(intent);
    }

    private void OpenBardoInsertDataByID() {

        Intent intent = new Intent(this , BardoTab.class);
        intent.putExtra("NameButton",NameButton);


        startActivity(intent);
    }


}

this is My SectionsPagerAdapter for the fragment Tab这是片段选项卡的 My SectionsPagerAdapter

package com.example.musepourtous.ui.main;



public class SectionsPagerAdapter extends FragmentPagerAdapter {
private  String NameButton;
    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
      Fragment fragment = null;
      switch (position)
      {
          case 0 :
              fragment  = new EnglishBardoFragment();
              /*Bundle bundle = new Bundle();
              bundle.getString("edttext");
              String test =  bundle.getString("edttext");
              bundle.putString("edttext1", "test");
              fragment.setArguments(bundle);*/
              break;
          case 1 :
              fragment = new FrenchBardo();
              break;
          case 2 :
              fragment = new ArabicBardoFragment();

      }
      return fragment;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 3;
    }
}

and this is my Fragment EnglishBardoFragment这是我的片段英文BardoFragment

public class EnglishBardoFragment extends Fragment {
    
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private  EditText UUIDBE , DescBE , TitleBE ;
    private Button SaveDataBE;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    DatabaseReference myRef ;

    private Button ChooseImageBE;
    private Button CancelBardoBE;
    private ImageView ImageViewBE;
    private ProgressBar ProgressBarBE;
    private ProgressBar ProgressBarBES;

    private Button ChooseSoundBE;



    private Uri ImageUri;
    private Uri SoundUri;
    private static final int PICK_IMAGE_REQEST = 1  ;
    private static final int PICK_SOUND_REQEST = 0  ;
    private StorageReference mStorageRef;
    private StorageReference mStorageRefS;
    private String ImageURLData ;
    private String SoundURLData ;

    private ImageView imagePlayPause;
    private TextView textCurrrentTime , textTotalDuration;
    private SeekBar playerSeekBar ;
    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
    String NameButton;


    public EnglishBardoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment EnglishBardoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EnglishBardoFragment newInstance(String param1, String param2) {
        EnglishBardoFragment fragment = new EnglishBardoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);

        return fragment;
    }
    private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }

    }

    @SuppressLint("WrongViewCast")
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        checkPermissions();

        myRef = FirebaseDatabase.getInstance().getReference();
        mStorageRef = FirebaseStorage.getInstance().getReference("Images");
        mStorageRefS = FirebaseStorage.getInstance().getReference("Sounds");
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_english_bardo, null);
        UUIDBE = (EditText) view.findViewById(R.id.UUIDBardoE);

        TitleBE = view.findViewById(R.id.TitleBardoE);

        DescBE = view.findViewById(R.id.DescriptionBardoE);
        SaveDataBE = view.findViewById(R.id.AddBeaconBE);
        ChooseImageBE = view.findViewById(R.id.CHooseImageBardoE);
        ImageViewBE = view.findViewById(R.id.imageViewBE);
        ProgressBarBE = view.findViewById(R.id.progress_bar);
        ProgressBarBES = view.findViewById(R.id.progress_barA);
        ChooseSoundBE = view.findViewById(R.id.CHooseSoundBardoE);
        imagePlayPause = view.findViewById(R.id.imagePlayPause);
        textCurrrentTime = view.findViewById(R.id.textCurrentTime);
        textTotalDuration = view.findViewById(R.id.textTotalDuration);
        playerSeekBar = view.findViewById(R.id.playerSeekBar);
        CancelBardoBE = view.findViewById(R.id.CancelBardoBE);


        mediaPlayer =  new MediaPlayer();
        playerSeekBar.setMax(100);
        imagePlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( mediaPlayer.isPlaying())
                {
                    handler.removeCallbacks(updater);
                    mediaPlayer.pause();
                    imagePlayPause.setImageResource(R.drawable.ic_play);
                    updateSeekBar();
                }
                else
                {
                    mediaPlayer.start();
                    imagePlayPause.setImageResource(R.drawable.ic_pause);
                    updateSeekBar();
                }

            }
        });


     

        return view;
    }

    private void preapareMediaPlayer(Uri path)
    {

            try {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDataSource(getActivity().getApplicationContext(), path);
                mediaPlayer.prepare();
                textTotalDuration.setText(milliSecondToTimer(mediaPlayer.getDuration()));

            }catch (Exception exception){
                Toast.makeText(getActivity(), exception.getMessage(), Toast.LENGTH_SHORT).show();
            }




    }
    private Runnable updater = new Runnable() {
        @Override
        public void run() {
            updateSeekBar();
            long currentDuration = mediaPlayer.getCurrentPosition();
            textCurrrentTime.setText(milliSecondToTimer(currentDuration));
        }
    };
    private void updateSeekBar()
    {
    if ( mediaPlayer.isPlaying())
    {
        playerSeekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
        handler.postDelayed(updater,1000);
    }
    }   
    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent , PICK_IMAGE_REQEST);

    }
    private void openSoundChooser() {
        Intent intent = new Intent();
        intent.setType("audio/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent , PICK_SOUND_REQEST);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( requestCode == PICK_IMAGE_REQEST && resultCode == RESULT_OK && data != null && data.getData() != null )
        {
            ImageUri = data.getData() ;
            Picasso.get().load("ImageUri").into(ImageViewBE);
            Picasso.get().load(ImageUri).into(ImageViewBE);

        }

      else  if( requestCode == PICK_SOUND_REQEST && resultCode == RESULT_OK && data != null && data.getData() != null )
        {

            SoundUri = data.getData() ;



            preapareMediaPlayer(SoundUri);



        }

    }



    private void UploadImage() {
        if (ImageUri != null )
        {
           final StorageReference fileReference = mStorageRef.child(UUIDBE.getText().toString());
           fileReference.putFile(ImageUri)
                   .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                       @Override
                       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                           Handler handler = new Handler();
                           handler.postDelayed(new Runnable() {
                               @Override
                               public void run() {
                                   ProgressBarBE.setProgress(0);
                               }
                           } ,  500);
                           fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                               @Override
                               public void onSuccess(Uri uri) {
                                   Uri downloadUrl = uri;
                                   ImageURLData = downloadUrl.toString();
                                   AddBeaconsBE();

                               }
                           });

                           Toast.makeText(getActivity(), "Upload Image  Successful", Toast.LENGTH_SHORT).show();



                       }
                   })
                   .addOnFailureListener(new OnFailureListener() {
                       @Override
                       public void onFailure(@NonNull Exception e) {
                           Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                       }
                   })
                   .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                       @Override
                       public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                           Toast.makeText(getActivity(), "Upload Image in progress", Toast.LENGTH_SHORT).show();
                          double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount() );
                           ProgressBarBE.setProgress((int) progress);
                       }

                   })
           .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
               @Override
               public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

               }
           });




        }
        else
        {
            Toast.makeText(getActivity(), "No Image Selected - Please Select Image before saving data", Toast.LENGTH_SHORT).show();
        }
    }




    public void AddBeaconsBE(){
        String UUIDBeacon = UUIDBE.getText().toString();
        String TitleBeacon = TitleBE.getText().toString();
        String DescriptionBeacon = DescBE.getText().toString();
        //Displaying Toast with Hello Javatpoint message

        if ( !TextUtils.isEmpty(UUIDBeacon) && !TextUtils.isEmpty(TitleBeacon) && !TextUtils.isEmpty(DescriptionBeacon))
        {
            String id = UUIDBeacon;

            DataBeacon beacons = new DataBeacon( UUIDBeacon , TitleBeacon , DescriptionBeacon , ImageURLData , SoundURLData , UUIDBE.getText().toString().trim() );

            myRef.child("0").child("Musees").child("Bardo").child("Beacons").child(id).setValue(beacons);




            BeaconsPosition beaconsposition = new BeaconsPosition( "191" ,"360"  );
            myRef.child("0").child("Musees").child("Bardo").child("Beacons").child(id).child("Position").setValue(beaconsposition);
            myRef.child("Positions").child(id).setValue(beaconsposition);

            Toast.makeText(getActivity(), "Beacon Added successfully", Toast.LENGTH_SHORT).show();

            UUIDBE.setText("");
            TitleBE.setText("");
            DescBE.setText("");
            ImageViewBE.setImageResource(0);
            mediaPlayer.stop();
            textTotalDuration.setText("0:0");
            imagePlayPause.setActivated(false);

        }
        if(TextUtils.isEmpty(UUIDBeacon)) {
            UUIDBE.setError("Please Enter The UUID");
            return;
        }
        if(TextUtils.isEmpty(TitleBeacon)) {
            TitleBE.setError("Please Enter The TITLE");
            return;
        }
        if(TextUtils.isEmpty(DescriptionBeacon)) {
            DescBE.setError("Please Enter The DESCRIPTION");
            return;
        }

    }
    private String getFileExtension(Uri uri) {
        ContentResolver cR =  getActivity().getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(cR.getType(uri));
    }

    protected void checkPermissions() {
        final List<String> missingPermissions = new ArrayList<String>();
        // check all required dynamic permissions
        for (final String permission : REQUIRED_SDK_PERMISSIONS) {
            final int result = ContextCompat.checkSelfPermission(getActivity(), permission);
            if (result != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add(permission);
            }
        }
        if (!missingPermissions.isEmpty()) {
            // request all missing permissions
            final String[] permissions = missingPermissions
                    .toArray(new String[missingPermissions.size()]);
            ActivityCompat.requestPermissions(getActivity(), permissions, REQUEST_CODE_ASK_PERMISSIONS);
        } else {
            final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
            Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
            onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
                    grantResults);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                for (int index = permissions.length - 1; index >= 0; --index) {
                    if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
                        // exit the app if one permission is not granted


                        return;
                    }
                }

                break;
        }
    }
}

这是我正在谈论的 bardoMap 活动的界面,黄色是我双击以将名称发送到 Fragment 的按钮

这是我想将值按钮发送给它的片段选项卡的界面,以便我可以用数据填充 Texfiled

PS: I delete some Unesesery function from my code because of the maximum code line that's why some function are culled but don't exist PS:我从我的代码中删除了一些 Unesesery function 因为最大的代码行这就是为什么一些 function 被剔除但不存在的原因

I found a solution by using PowerPreference我通过使用PowerPreference找到了解决方案

I did this in my MainActivity我在我的 MainActivity 中做了这个

 NameButton = ((Button) v).getText().toString();
 PowerPreference.getDefaultFile().putString("key",NameButton);

Then I called it the fragment然后我称它为片段

value = PowerPreference.getDefaultFile().getString("key", NameButton);

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

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