我只是无法让片段工作

Posted

技术标签:

【中文标题】我只是无法让片段工作【英文标题】:I just can't get a fragment to work 【发布时间】:2015-09-12 05:53:27 【问题描述】:

我只是想添加最简单的片段,我显然做错了什么。我在 android Studio 中创建了一个空白的“MainActivity”,然后添加了一个片段并尝试将其连接起来:

MainActivity.java:

package com.fragtester.fragtester.fragtester;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity 

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

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) 

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) 
                return;
            

            // Create a new Fragment to be placed in the activity layout
            BlankFragment firstFragment = new BlankFragment();

            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) 
            return true;
        

        return super.onOptionsItemSelected(item);
    

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_
    android:layout_ android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_
        android:layout_ />

</RelativeLayout>

BlankFragment.java

package com.fragtester.fragtester.fragtester;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple @link Fragment subclass.
 * Activities that contain this fragment must implement the
 * @link BlankFragment.OnFragmentInteractionListener interface
 * to handle interaction events.
 * Use the @link BlankFragment#newInstance factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends android.support.v4.app.Fragment 
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * 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 BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) 
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    

    public BlankFragment() 
        // Required empty public constructor
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        if (getArguments() != null) 
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) 
        if (mListener != null) 
            mListener.onFragmentInteraction(uri);
        
    

    @Override
    public void onAttach(Activity activity) 
        super.onAttach(activity);
        try 
            mListener = (OnFragmentInteractionListener) activity;
         catch (ClassCastException e) 
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        
    

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

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener 
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    


fragment_blank.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_
    android:layout_
    tools:context="com.fragtester.fragtester.fragtester.BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView android:layout_ android:layout_
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

我做错了什么?!?!?我已经完成了许多不同的教程,但我无法让它为我工作。请帮忙!我很沮丧。

【问题讨论】:

您是否有特定错误或没有显示任何内容? 您是否遇到任何错误?如果是,则发布 logcat 的堆栈跟踪。 【参考方案1】:

您是否遇到任何错误?因为通过查看您的代码,我可以看到您已经创建了一个默认片段,并且它自动为您的片段添加了一个回调接口,您的MainActivity 类没有实现。我敢肯定,如果您查看 Logcat,您会看到一条错误消息,其中包含 "MainActivity must implement OnFragmentInteractionListener" 行的消息。

以后,学习检查 Logcat 并发布您的堆栈跟踪(如果有的话),这将使获得答案变得更加容易。

要解决此问题,您应该从片段中删除回调接口,因为我确信您此时不需要它。为此,请从BlankFragment删除以下代码行:

private OnFragmentInteractionListener mListener;

// ...

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) 
    if (mListener != null) 
        mListener.onFragmentInteraction(uri);
    


@Override
public void onAttach(Activity activity) 
    super.onAttach(activity);
    try 
        mListener = (OnFragmentInteractionListener) activity;
     catch (ClassCastException e) 
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    


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


/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener 
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);

【讨论】:

谢谢!这是有道理的。我实际上已经研究了回调接口并使其正常工作。谢谢你的帮助!!!!【参考方案2】:

我也遇到过这个错误,但是当我更改导入时 android.app.Fragment android.support.v4.app.Fragment

比它对我有用。

尝试在您的 BlankFragment 类中进行这些更改。

【讨论】:

【参考方案3】:

尝试在您的班级中实现所需的onFragmentInteractionListener

public class SecondScreen extends AppCompatActivity implements HomeFragment.OnFragmentInteractionListener,
    NewsFragment.OnFragmentInteractionListener, services.OnFragmentInteractionListener,
    SettingFragment.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener 

像这样覆盖 main.java 中的onFragmentInteraction

    @Override
public void onFragmentInteraction(Uri uri) 


希望对你有帮助

【讨论】:

以上是关于我只是无法让片段工作的主要内容,如果未能解决你的问题,请参考以下文章

使用 savedInstanceState 保存片段状态

我的片段中的按钮无法识别

OnClick 在片段的回收器适配器中无法正常工作

使用片段共享过渡时返回过渡无法正常工作

无法让 UITableViewAutomaticDimension 正常工作

无法让 mysqldump 工作