使用FragmentManager时无法识别的类型

时间:2019-03-28 20:29:16

标签: android android-fragments android-fragmentactivity fragmentmanager

我正在尝试使用另一个片段从一个片段中调用方法。我试图按照这里的答案,但我一直得到难以理解的类型。我将包括进口。

ListFragment.java

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_list,null);
        ListView list1 = (ListView)view.findViewById(R.id.listview1);
        ActivityManager am = (ActivityManager)getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager packageManager = getActivity().getPackageManager();
        ArrayAdapter<String> aa;

        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
        final String pnArr[] = new String[runningAppProcessInfo.size()];
        List<String> filteredApps = new ArrayList<>();
        final List<String> filteredRunningApps = new ArrayList<>();
        final List<String> appNames = new ArrayList<>();

        //user-apps loop
        List<PackageInfo> apps = getActivity().getPackageManager().getInstalledPackages(0);
        for (int i = 0; i < apps.size(); i++){
            if ((apps.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 1){
                filteredApps.add(apps.get(i).packageName);
            }
        }

        //running apps + comparison loop
        for (int i = 0; i < runningAppProcessInfo.size(); i++) {
            pnArr[i] = runningAppProcessInfo.get(i).processName;
            if (filteredApps.contains(runningAppProcessInfo.get(i).processName)) {
                filteredRunningApps.add(runningAppProcessInfo.get(i).processName);
            }
        }

        //package name -> app name conversion
        for (int i = 0; i < filteredRunningApps.size();i++) {
            ApplicationInfo ai = null;
            try{
                ai = packageManager.getApplicationInfo(filteredRunningApps.get(i),0);

            }catch (PackageManager.NameNotFoundException e){}
            String title = (String)((ai != null) ? packageManager.getApplicationLabel(ai) : "???");
            appNames.add(title);
        }

        Toast.makeText(getActivity(), "Filtered Apps : " + filteredApps.size() + " | Running Apps : " + runningAppProcessInfo.size() + " | Filtered Running Apps : " + filteredRunningApps.size(), Toast.LENGTH_LONG).show();

         ArrayList<String> pnList = new ArrayList<String>();
         pnList.addAll(Arrays.asList(pnArr));
         aa = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,appNames);
         list1.setAdapter(aa);
         aa.notifyDataSetChanged();

         list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                 //Toast.makeText(getActivity(), filteredRunningApps.get(position), Toast.LENGTH_SHORT).show();

                 AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
                 adb.setTitle("Monitor " + appNames.get(position) + "?");
                 adb.setMessage("Times the application.");

                 adb.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                             //tf.startTime();
                         Toast.makeText(getActivity(), "Currently monitoring " + appNames.get(position) + ".", Toast.LENGTH_SHORT).show();
                        FragmentManager fm = getFragmentManager();
                        MainActivity frag = (MainActivity)fm.findFragmentById(R.id.id_frag);

                     }
                 });

                 adb.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         Toast.makeText(getActivity(), "gg", Toast.LENGTH_SHORT).show();
                     }
                 });

                 adb.show();
             }
         });

        return view;
    }
}

这里唯一错误的行是:

FragmentManager fm = getFragmentManager();
MainActivity frag = (MainActivity)fm.findFragmentById(R.id.id_frag);

我扩展了支持片段,但是当我使用getSupportFragmentManager()时,我得到了一个无法解析方法。

MainActivity.java

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

 public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

private final Fragment mTimerFragment = new TimerFragment();
private final Fragment mListFragment = new ListFragment();
private final Fragment mReminderFragment = new RemindFragment();

private Fragment mActiveFragment = mTimerFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager().beginTransaction()
        .add(R.id.fragContainer, mReminderFragment, "TimerFragment")
        .hide(mReminderFragment)
        .commit();
        getSupportFragmentManager().beginTransaction()
        .add(R.id.fragContainer, mListFragment, "ListFragment")
        .hide(mListFragment)
        .commit();
        getSupportFragmentManager().beginTransaction()
        .add(R.id.fragContainer, mTimerFragment, "ReminderFragment")
        .commit();

        BottomNavigationView navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(this);
        }

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
        case R.id.navigation_home:
        getSupportFragmentManager().beginTransaction()
        .hide(mActiveFragment)
        .show(mTimerFragment)
        .commit();
        mActiveFragment = mTimerFragment;
        return true;
        case R.id.navigation_dashboard:
        getSupportFragmentManager().beginTransaction()
        .hide(mActiveFragment)
        .show(mListFragment)
        .commit();
        mActiveFragment = mListFragment;
        return true;
        case R.id.navigation_notifications:
        getSupportFragmentManager().beginTransaction()
        .hide(mActiveFragment)
        .show(mReminderFragment)
        .commit();
        mActiveFragment = mReminderFragment;
        return true;
        }

        return false;
        }
        }

TimerFragment.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimerFragment extends Fragment {
    Button btnMonitor;
    Button btnRemind;
    TimePicker tp;
    CountDownTimer cdt;
    TextView tvTimer, tvRemind;
    long startTime = 0;
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            long millis = System.currentTimeMillis() - startTime;
            int seconds = (int)(millis/1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tvTimer.setText(String.format("%d:%02d", minutes, seconds));
            timerHandler.postDelayed(this,500);
        }
    };



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_timer, null);
        tp = (TimePicker)view.findViewById(R.id.timepick1);
        tvTimer = (TextView)view.findViewById(R.id.tvTimer);
        tvRemind = view.findViewById(R.id.textView3);
        btnMonitor = (Button)view.findViewById(R.id.btn1);
        btnRemind = (Button)view.findViewById(R.id.btn2);

        btnRemind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar cal = Calendar.getInstance();

                //current
                Date c = cal.getTime();
                long currentTime = c.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy h:mm a");
                //String d = sdf.format(c); //output 27/03/2019 3:05 AM

                //timepicker time
                String tpTime = String.valueOf(tp.getCurrentHour()) +":"+ String.valueOf(tp.getCurrentMinute());
                int tpDateDay = cal.get(Calendar.DAY_OF_MONTH);
                int tpDateMonth = cal.get(Calendar.MONTH);
                int tpDateYear = cal.get(Calendar.YEAR);
                Calendar c2 = Calendar.getInstance();
                c2.set(tpDateYear,tpDateMonth,tpDateDay,tp.getCurrentHour(),tp.getCurrentMinute(),0);
                long tpMillis = c2.getTimeInMillis();

                long remaining = tpMillis - currentTime;

                Toast.makeText(getActivity(),"Remaining time "+ remaining/1000, Toast.LENGTH_SHORT).show();

                cdt = new CountDownTimer(remaining,1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        tvRemind.setText(" " + millisUntilFinished/1000 + " seconds");
                    }

                    @Override
                    public void onFinish() {
                        Intent intent = new Intent (getActivity(),MainActivity.class);
                        PendingIntent pIntent = PendingIntent.getActivity(getActivity(),(int)System.currentTimeMillis(),intent,0);
                        Notification n = new Notification.Builder(getActivity())
                                .setContentTitle("Time is up!")
                                .setContentText("Consider stopping the application now.")
                                .setSmallIcon(R.drawable.ic_notifications_black_24dp)
                                .setContentIntent(pIntent)
                                .setAutoCancel(true)
                                .build();
                        NotificationManager nm =  (NotificationManager)getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
                        nm.notify(0,n);

                        tvRemind.setText("0");
                    }
                }.start();
            }
        });

        btnMonitor.setText("Start");
        btnMonitor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Button b = (Button) v;

                if (b.getText().equals("Stop")){
                    timerHandler.removeCallbacks(timerRunnable);
                    b.setText("Start Monitoring");
                }

                else {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                    b.setText("Stop");
                    Toast.makeText(getActivity(),"Monitoring started.",Toast.LENGTH_SHORT).show();
                }
            }
        });

        return view;
    }

    public void startTime() {
        timerHandler.postDelayed(timerRunnable,0);
    }
}

我要调用的方法是startTime() 这些是我尝试过的,但无济于事。 Call an activity method from a fragment

Call an method in one fragment from another

如何在没有所有这些错误的情况下引用该片段?

1 个答案:

答案 0 :(得分:0)

您无法通过片段管理器获得活动

FragmentManager fm = getFragmentManager();
MainActivity frag = (MainActivity)fm.findFragmentById(R.id.id_frag);

使用

getActivity() or requireActivity()

此外,您可能会从阅读https://developer.android.com/training/basics/fragments/communicating

中受益