Java 如何将 FloatingActionButton 放入 Fragment?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39036383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:49:40  来源:igfitidea点击:

How to put FloatingActionButton to Fragment?

javaandroidandroid-fragments

提问by J. Shmoe

How can I put my fabon my fragment? help please I'm getting errors such as.

我怎样才能把我的fab放在我的片段上?请帮助我收到错误,例如。

android.view.InflateException: Binary XML file line #13: Error inflating class fragment

android.view.InflateException:二进制 XML 文件第 13 行:错误膨胀类片段

in my fragment acticity. Well here are my codes.

在我的片段活动中。那么这里是我的代码。

well the problem is in the getActivity().setContentView(R.layout.activity_ownerhome);

那么问题出在 getActivity().setContentView(R.layout.activity_ownerhome);

#ownerhome.java

public class ownerhome extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ownerhome);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    }

}

ownerhomeFragment.java

ownerhomeFragment.java

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


    ImageLoader.getInstance().init(UILConfig.config(getActivity()));
    lvCars = (ListView) v.findViewById(R.id.lvOnwer);

    pref = getActivity().getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
    Log.d(TAG, pref.getString("username", ""));
    Log.d(TAG, pref.getString("password", ""));


    PostResponseAsyncTask taskRead = new PostResponseAsyncTask(getActivity(), this);
    tvUser = (TextView) v.findViewById(R.id.tvUser);
    tvUser.setText("Hello! "+pref.getString("username", ""));

    taskRead.execute("http://carkila.esy.es/user.php?owner="+pref.getString("username", ""));

    FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent in = new Intent(getActivity(), InsertActivity.class);
            startActivity(in);
        }
    });
    registerForContextMenu(lvCars);
    return v;
}

content_ownerhome.xml

content_ownerhome.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.kun.carkila.ownerhome"
tools:showIn="@layout/activity_ownerhome">

<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.kun.carkila.ownerFragment"
android:id="@+id/ownerhomeFragment"/>

</RelativeLayout>

activity_ownerhome.xml

活动所有者主页.xml

<?xml version="1.0" encoding="utf-8"?>    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.kun.carkila.ownerhome">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_ownerhome" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/plus" />


</android.support.design.widget.CoordinatorLayout>

fragmentOwnerHome.xml

fragmentOwnerHome.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.kun.carkila.ownerhome"
tools:showIn="@layout/activity_ownerhome">


<ListView
    android:layout_width="match_parent"
    android:layout_height="450sp"
    android:id="@+id/lvOnwer"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="24dp"
    android:textSize="30sp"
    android:textColor="@color/colorPrimaryDark"
    android:id="@+id/tvUser" />

</RelativeLayout>

STACK TRACE

堆栈跟踪

FATAL EXCEPTION: main
Process: com.example.kun.carkila, PID: 9267
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kun.carkila/com.example.kun.carkila.ownerhome}: android.view.InflateException: Binary XML file line #12: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access0(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.kun.carkila.ownerFragment.onCreateView(ownerFragment.java:127)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2288)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:356)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.kun.carkila.ownerhome.onCreate(ownerhome.java:12)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)?
at android.app.ActivityThread.access0(ActivityThread.java:135)?
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)?
at android.os.Handler.dispatchMessage(Handler.java:102)?
at android.os.Looper.loop(Looper.java:136)?
at android.app.ActivityThread.main(ActivityThread.java:5021)?
at java.lang.reflect.Method.invokeNative(Native Method)?
at java.lang.reflect.Method.invoke(Method.java:515)?
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)?
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)?
at dalvik.system.NativeStart.main(Native Method)?
Caused by: java.lang.IllegalArgumentException: Binary XML file line #12: Duplicate id 0x7f0e00aa, tag null, or parent id 0xffffffff with another fragment for com.example.kun.carkila.ownerFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity

采纳答案by Hasan shaikh

You have added the floating action button in your activity_ownerhome.xml and you are initializing it in ownerhomeFragment.java.

您已在 activity_ownerhome.xml 中添加了浮动操作按钮,并且正在 ownerhomeFragment.java 中对其进行初始化。

So add your FloatingActionButton in fragmentownerhome.xml itself like this

所以像这样在 fragmentownerhome.xml 本身中添加你的 FloatingActionButton

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layout_behavior="@string/appbar_scrolling_view_behavior"
  tools:context="com.example.kun.carkila.ownerhome"
  tools:showIn="@layout/activity_ownerhome">

  <ListView
    android:layout_width="match_parent"
    android:layout_height="450sp"
    android:id="@+id/lvOnwer"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true" />

  <TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="24dp"
    android:textSize="30sp"
    android:textColor="@color/colorPrimaryDark"
    android:id="@+id/tvUser" />

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/plus" />
</RelativeLayout>

and remove the FloatingActionButton from your activity_ownerhome.xml file.

并从您的 activity_ownerhome.xml 文件中删除 FloatingActionButton。

回答by amitairos

The problem isn't with the FAB, it's with how you inflate your view.
Replace this code in the Fragment:

问题不在于 FAB,而在于你如何夸大你的观点。
在 Fragment 中替换此代码:

View v = super.onCreateView(inflater, container, savedInstanceState);
getActivity().setContentView(R.layout.activity_ownerhome);

With this:

有了这个:

var v = inflater.inflate(R.layout.{your fragment xml}, container, false);

And remove this:

并删除这个:

 <fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.kun.carkila.ownerFragment"
android:id="@+id/ownerhomeFragment"/>

You should define how you want your fragment xml to look, and then inflate it using the code inflater.inflate...and put in your fragment xml there, like I wrote above.

您应该定义您希望片段 xml 的外观,然后使用代码对其进行扩充inflater.inflate...并将您的片段 xml 放入其中,就像我上面写的那样。

Update:
Instead of <include layout="@layout/content_ownerhome" />place in this:

更新:
而不是<include layout="@layout/content_ownerhome" />在这个地方:

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/content_frame" />

Then in your Main Activity write this code:

然后在您的主活动中编写以下代码:

 getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();

And you're supposed to see your fragment, if in the fragment you inflated your fragment xml correctly, as stated above.

并且你应该看到你的片段,如果你在片段中正确地膨胀了你的片段 xml,如上所述。

回答by Bukunmi

The cause of the crash is because your FAB xml code is in the "Activity layout", it is supposed to be in the "fragment layout" file

崩溃的原因是因为你的FAB xml代码在“Activity layout”中,应该在“fragment layout”文件中

This is how i use FAB in a fragment

这就是我在片段中使用 FAB 的方式

In my fragment layout file:

在我的片段布局文件中:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

In my fragment class file:

在我的片段类文件中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    return view;
}

And it works...

它有效...

NOTE:when i included android:backgroundTint="@android:color/transparent" the application crashed and gave the error :

注意:当我包含android:backgroundTint="@android:color/transparent" 应用程序崩溃并给出错误时:

Binary XML file line #14: Error inflating class android.support.design.widget.FloatingActionButton

Hope this helps.

希望这可以帮助。

回答by jose luis Ribero

You must implement the fragment in your main class something like...

您必须在主类中实现片段,例如...

public class ownerhome extends AppCompatActivity implement ownerhomeFragment {...