android意图片段到活动有错误

Posted

技术标签:

【中文标题】android意图片段到活动有错误【英文标题】:Have error with android intent fragment to activity 【发布时间】:2021-02-05 03:20:16 【问题描述】:

*帮助我找出错误的原因。 我做了 onClick mButtonDate 我的清单中有问题。 我需要向您展示哪些文件以便您了解我的问题? 我试图更改清单,关闭 InstantRun,重建项目,谷歌搜索问题。 *

public class CrimeFragment extends Fragment 

    private static final String ARG_CRIME_ID = "crime_id";
    private static final String DATE_DIALOG = "DialogDate";
    private static final String TIME_DIALOG = "DialogTime";

    public static final String TIME_FORMAT = "hh:mm: a z";

    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_TIME = 1;

    private Crime mCrime;
    private EditText mTitleField;
    private Button mButtonDate;
    private Button mButtonTime;
    private CheckBox mCheckSolvedBox;
    private Button firstButton;
    private Button lastButton;

    private boolean mIsLargeLayout;
    private Callbacks mCallbacks;

    public interface Callbacks 
        void onCrimeUpdate(Crime crime);
    

    public static CrimeFragment newInstanse(UUID crimeId) 

        Bundle args = new Bundle();
        args.putSerializable(ARG_CRIME_ID, crimeId);

        CrimeFragment fragment = new CrimeFragment();
        fragment.setArguments(args);
        return fragment;
    

    @Override
    public void onAttach(@NonNull Context context) 
        super.onAttach(context);
        mCallbacks = (Callbacks) context;
    

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);

        mIsLargeLayout = getResources().getBoolean(R.bool.large_layout);

        UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
        mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
    

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        View v = inflater.inflate(R.layout.fragment_crime, container, false);

        firstButton = v.findViewById(R.id.firstButton);
        lastButton = v.findViewById(R.id.lastButton);

        mCheckSolvedBox = (CheckBox) v.findViewById(R.id.crime_solved);
        mCheckSolvedBox.setChecked(mCrime.isSolved());
        mCheckSolvedBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
                mCrime.setSolved(isChecked);
                updateCrime();
            
        );

        mButtonTime = (Button) v.findViewById(R.id.crime_time);
        updateTime();
        mButtonTime.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if (mIsLargeLayout) 
                    FragmentManager fragment = getFragmentManager();
                    TimePickerFragment dialog = TimePickerFragment.newInstance(mCrime.getTime());
                    dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
                    dialog.show(fragment, TIME_DIALOG);
                 else 
                    Intent intent = TimePickerActivity.newIntent(getContext(), mCrime.getTime());
                    startActivityForResult(intent, REQUEST_TIME);
                
            
        );

        mButtonDate = (Button) v.findViewById(R.id.crime_date);
        updateDate();
        mButtonDate.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if (mIsLargeLayout) 
                    FragmentManager fragmentManager = getFragmentManager();
                    DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
                    dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                    dialog.show(fragmentManager, DATE_DIALOG);
                 else 
                    Intent intent = DatePickerActivity.newIntent(getContext(), mCrime.getDate());
                    startActivityForResult(intent, REQUEST_DATE);
                
            
        );

        mTitleField = (EditText) v.findViewById(R.id.crime_title);
        mTitleField.setText(mCrime.getTitle());
        mTitleField.addTextChangedListener(new TextWatcher() 
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) 

            

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) 
                mCrime.setTitle(s.toString());
                updateCrime();

            

            @Override
            public void afterTextChanged(Editable s) 

            
        );

        firstButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                ((CrimePagerActivity) getActivity()).goToFistPage();
            
        );

        lastButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                ((CrimePagerActivity) getActivity()).goToLastPage();
            
        );


        return v;
    

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
        if (resultCode != Activity.RESULT_OK) 
            return;
        
        if (requestCode == REQUEST_DATE) 
            Date date = (Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            mCrime.setDate(date);
            updateDate();
            updateCrime();
        
        if (requestCode == REQUEST_TIME) 
            Date time = (Date) data.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
            mCrime.setTime(time);
            updateTime();
            updateCrime();
        
    

    private void updateCrime() 
        mCallbacks.onCrimeUpdate(mCrime);
    

    private void updateDate() 
        mButtonDate.setText(mCrime.getDate().toString());
    

    private void updateTime() 
        DateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
        mButtonTime.setText(timeFormat.format(mCrime.getTime()));

    

    @Override
    public void onDetach() 
        super.onDetach();
        mCallbacks = null;
    

startActivityForResult 中的错误(意图,REQUEST_DATE); :

    mButtonDate = (Button) v.findViewById(R.id.crime_date);
    updateDate();
    mButtonDate.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            if (mIsLargeLayout) 
                FragmentManager fragmentManager = getFragmentManager();
                DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
                dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                dialog.show(fragmentManager, DATE_DIALOG);
             else 
                Intent intent = DatePickerActivity.newIntent(getContext(), mCrime.getDate());
                startActivityForResult(intent, REQUEST_DATE);
            
        
    );

错误:

    2020-10-21 23:03:59.853 18523-18523/com.example.criminalintent E/androidRuntime: FATAL EXCEPTION: main
    Process: com.example.criminalintent, PID: 18523
    android.content.ActivityNotFoundException: Unable to find explicit activity class com.example.criminalintent/com.example.criminalintent.DatePickerFragment; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1932)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1615)
        at android.app.Activity.startActivityForResult(Activity.java:4472)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at androidx.core.app.ActivityCompat.startActivityForResult(ActivityCompat.java:234)
        at androidx.fragment.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:796)
        at androidx.fragment.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:933)
        at androidx.fragment.app.Fragment.startActivityForResult(Fragment.java:1206)
        at androidx.fragment.app.Fragment.startActivityForResult(Fragment.java:1194)
        at com.example.criminalintent.CrimeFragment$3.onClick(CrimeFragment.java:128)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

我的清单:

    <?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.criminalintent">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".CrimeListActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".CrimePagerActivity">
        </activity>

    </application>
</manifest>

日期选择器片段:

public class DatePickerFragment extends DialogFragment 

    private static final String ARG_DATE = "Date";

    public static final String EXTRA_DATE = "com.example.criminalintent.date";

    private DatePicker mDatePicker;
    private Button mDatePickerOkButton;

    public static DatePickerFragment newInstance(Date date) 
        Bundle args = new Bundle();
        args.putSerializable(ARG_DATE, date);

        DatePickerFragment fragment = new DatePickerFragment();
        fragment.setArguments(args);
        return fragment;
    

    @NonNull
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        Date date = (Date) getArguments().getSerializable(ARG_DATE);

        View v = inflater.inflate(R.layout.dialog_date, container, false);


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        mDatePicker = (DatePicker) v.findViewById(R.id.dialog_date_picker);
        mDatePicker.init(year, month, day, null);

        mDatePickerOkButton = (Button) v.findViewById(R.id.dialog_date_ok_button);
        mDatePickerOkButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                int year = mDatePicker.getYear();
                int month = mDatePicker.getMonth();
                int day = mDatePicker.getDayOfMonth();
                Date date = new GregorianCalendar(year, month, day).getTime();
                sendResult(Activity.RESULT_OK, date);
            
        );

        return v;

    

    private void sendResult(int resultCode, Date date)
        Intent data = new Intent();
        data.putExtra(EXTRA_DATE, date);

        if (getTargetFragment() == null) 
            Activity hostingActivity = getActivity();
            hostingActivity.setResult(resultCode, data);
            hostingActivity.finish();
         else 
 

           dismiss();
            getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, data);
        
    

日期选择器活动:

public class DatePickerActivity extends SingleFragmentActivity 

private static final String EXTRA_CRIME_DATE = "com.example.criminalintent.crime_date";

public static Intent newIntent(Context packageContext, Date date) 
    Intent intent = new Intent(packageContext, DatePickerActivity.class);
    intent.putExtra(EXTRA_CRIME_DATE, date);
    return intent;


@Override
protected Fragment createFragment() 
    Date date = (Date) getIntent().getSerializableExtra(EXTRA_CRIME_DATE);
    return DatePickerFragment.newInstance(date);

CrimeListAcrivity

public class CrimeListActivity extends SingleFragmentActivity implements CrimeListFragment.Callbacks, CrimeFragment.Callbacks 


@Override
protected Fragment createFragment() 
    return new CrimeListFragment();


@Override
protected int getLayoutResId() 
    return R.layout.activity_masterdetail;


@Override
public void onCrimeSelected(Crime crime) 
    if (findViewById(R.id.detail_fragment_container) == null) 
        Intent intent = CrimePagerActivity.newIntent(this, crime.getId());
        startActivity(intent);
     else 

        Fragment newDetail  = CrimeFragment.newInstanse(crime.getId());

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.detail_fragment_container, newDetail)
                .commit();
    


@Override
public void onCrimeUpdate(Crime crime) 
    CrimeListFragment listFragment = (CrimeListFragment)getSupportFragmentManager()
            .findFragmentById(R.id.fragment_container);
    listFragment.updateUI();

CrimePagerActivity

public class CrimePagerActivity extends AppCompatActivity implements  CrimeFragment.Callbacks 

private ViewPager mViewPager;
private List<Crime> mCrimes;
private static final String EXTRA_CRIME_ID = "com.example.criminalintent.crime_id";


public static Intent newIntent(Context packageContext, UUID crimeId) 
    Intent intent = new Intent(packageContext, CrimePagerActivity.class);
    intent.putExtra(EXTRA_CRIME_ID, crimeId);
    return intent;


public void goToFistPage() 
    mViewPager.setCurrentItem(0);


public void goToLastPage() 
    mViewPager.setCurrentItem(mCrimes.size());


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime_pager);

    UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);

    mViewPager = (ViewPager) findViewById(R.id.crime_view_pager);

    mCrimes = CrimeLab.get(this).getCrimes();

    FragmentManager fragmentManager = getSupportFragmentManager();
    mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) 

        @Override
        public Fragment getItem(int position) 

            Crime crime = mCrimes.get(position);
            return CrimeFragment.newInstanse(crime.getId());
        

        @Override
        public int getCount() 
            return mCrimes.size();
        
    );


    for (int i = 0; i < mCrimes.size(); i++) 
        if (mCrimes.get(i).getId().equals(crimeId)) 
            mViewPager.setCurrentItem(i);
            break;
        
    


@Override
public void onCrimeUpdate(Crime crime) 



@Override
public void onCrimeSelected(Crime crime) 


犯罪列表片段

public class CrimeListFragment extends Fragment 

private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;

private Callbacks mCallbacks;

/**
 * Required interface for hosting activities
 */

public interface Callbacks 
    void onCrimeSelected(Crime crime);



@Override
public void onAttach(@NonNull Context context) 
    super.onAttach(context);
    mCallbacks = (Callbacks) context;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    View v = inflater.inflate(R.layout.fragment_crime_list, container, false);


    mCrimeRecyclerView = (RecyclerView) v.findViewById(R.id.crime_recycler_view);
    mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    updateUI();

    return v;



@Override
public void onResume() 
    super.onResume();
    updateUI();


public void updateUI() 

    CrimeLab crimeLab = CrimeLab.get(getActivity());
    List<Crime> crimes = crimeLab.getCrimes();

    if (mAdapter == null) 
        mAdapter = new CrimeAdapter(crimes);
        mCrimeRecyclerView.setAdapter(mAdapter);
     else 
        for (int indexValue = 0; indexValue < crimes.size(); indexValue++) 
            mAdapter.notifyItemChanged(indexValue);
        
    



private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener 

    private Crime mCrime;
    private TextView mTitleTextView;
    private TextView mDateTextView;
    private ImageView mSolvedImageView;


    public CrimeHolder(LayoutInflater inflater, ViewGroup parent) 
        super(inflater.inflate(R.layout.list_item_crime, parent, false));
        itemView.setOnClickListener(this);

        mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
        mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);


    

    public void bind(Crime crime) 
        mCrime = crime;
        mTitleTextView.setText(mCrime.getTitle());
        mDateTextView.setText((String) DateFormat.format("EEEE, MMM dd, yyyy", mCrime.getDate()));
        mSolvedImageView.setVisibility(crime.isSolved() ? View.VISIBLE : View.GONE);
    

    @Override
    public void onClick(View v) 
        mCallbacks.onCrimeSelected(mCrime);
    


private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> 
    private List<Crime> mCrimes;


    public CrimeAdapter(List<Crime> crimes) 
        mCrimes = crimes;
    

    @Override
    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) 
        LayoutInflater layoutInFlater = LayoutInflater.from(getActivity());


        return new CrimeHolder(layoutInFlater, parent);
    

    @Override
    public void onBindViewHolder(CrimeHolder holder, int position) 
        Crime crime = mCrimes.get(position);
        holder.bind(crime);


    

    @Override
    public int getItemCount() 
        return mCrimes.size();
    



@Override
public void onDetach() 
    super.onDetach();
    mCallbacks = null;

SingleFragmentActivity

public abstract class SingleFragmentActivity extends AppCompatActivity 

protected abstract Fragment createFragment();

@LayoutRes
protected  int getLayoutResId()
    return  R.layout.activity_fragment;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(getLayoutResId());

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);

    if (fragment == null) 
        fragment = createFragment();
        fm.beginTransaction()
                .add(R.id.fragment_container, fragment)
                .commit();
    

【问题讨论】:

那么,您是否尝试过将 DatePickerFragment 添加到清单中? 不,因为我无法在清单中添加片段,但我添加了不同的活动,但什么也没发生。我看到了同样的问题。 github.com/Zblol/ThirdTrainingApp/tree/master/app/src/main/java/… 这是我的项目上的链接,也许有助于理解 【参考方案1】:
mButtonDate.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 

            FragmentManager fragmentManager = getFragmentManager();

            if (mIsLargeLayout) 
                DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
                dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                dialog.show(fragmentManager, DATE_DIALOG);
             else 
                final Dialog dialog_date = new Dialog(getContext());
                dialog_date.setContentView(R.layout.dialog_date);

                final DatePicker dialog_date_picker = dialog_date.findViewById(R.id.dialog_date_picker);
                Button dialog_date_ok_button = dialog_date.findViewById(R.id.dialog_date_ok_button);
                dialog_date_ok_button.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v) 
                        dialog_date.dismiss();
                        Toast.makeText(getContext(), dialog_date_picker.getYear() + "", Toast.LENGTH_SHORT).show();
                    
                );

                dialog_date.show();
            
        
    );

【讨论】:

它可以工作,但日历打开就像活动中的对话框一样,但我需要完全像活动一样打开 (DatePikerActivity) 我已经编辑了我的答案以从对话框中返回结果,并且不需要 DatePickerFragment 谢谢,但是很抱歉,我在其他类中使用了这些方法,我在上面添加了它们。

以上是关于android意图片段到活动有错误的主要内容,如果未能解决你的问题,请参考以下文章

在Android中将数据从活动发送到片段

设置onclick侦听器在android中无法从一个片段移动到另一个活动[重复]

片段中的意图不断与清单崩溃问题,android studio

Android在活动视图中附加片段获取片段已添加错误

片段中的Android选择器意图到图片照片

从 Fragment 到 Activity 的意图 - Android Java