Отправить имя кнопки из MainActivity во фрагмент - PullRequest
0 голосов
/ 03 августа 2020

Я новичок в разработке Android Studio JAVA, и это мой первый проект и опыт работы как в JAVA, так и android studio. Моя проблема в том, что я пытаюсь отправить имя кнопки двойным щелчком из основного действия под названием BardoMap во фрагмент вкладки (чтобы указать c фрагмент с именем EnglishBardoFragment ), поэтому Я могу использовать кнопку «Имя» для вызова некоторых данных из FireBase. Я вообще пытался использовать Bundle, но не смог найти правильного решения, чтобы отправлять имя кнопки только во фрагмент, который мне удается выполнить всю остальную работу, может ли кто-нибудь помочь мне с какой-то идеей или информацией о том, как это значение от активности до указанного c фрагмент

это код 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);
    }


}

это 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;
    }
}

и это мой фрагмент EnglishBardoFragment

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;
        }
    }
}

This is the interface of bardoMap activity that I'm talking about and on yellow is the button that I double click to send there Name to Fragment

это интерфейс вкладок фрагментов, которым я хочу отправить ему кнопку Value, чтобы я мог заполнить Texfiled данными

PS: Я удаляю некоторую функцию Unesesery из своего кода из-за максимальной строки кода, поэтому некоторые функции отбираются, но не существуют

1 Ответ

0 голосов
/ 04 августа 2020

Я нашел решение, используя PowerPreference

Я сделал это в своей MainActivity

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

Затем я назвал его фрагментом

value = PowerPreference.getDefaultFile().getString("key", NameButton);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...