简体   繁体   English

如何在Android Studio中使用Inflater从片段获取列表视图

[英]How to Using inflater to get a list view from fragment in Android Studio

I am trying to get a list view id from another xml file (fragment_friends.xml) while i am in activity_main.xml layout. 当我处于activity_main.xml布局时,我试图从另一个xml文件(fragment_friends.xml)获取列表视图ID。 I tried 2 ways, but they are not working properly. 我尝试了两种方法,但是它们无法正常工作。

Below code will cause the app to crash straight away because i am trying to get an id that does not exist in this layout (activity_main) 下面的代码将导致应用程序立即崩溃,因为我正在尝试获取此布局中不存在的ID(activity_main)

Original code 原始码

    ListView friendList = (ListView) findViewById(R.id.friend_listView);
    friendList.setAdapter(friendAdaptor);

Below code works, but i wont be able to insert or display any data into my database. 下面的代码有效,但是我将无法在数据库中插入或显示任何数据。

Try 1 code: 尝试1个代码:

    View inflatedView = getLayoutInflater().inflate(R.layout.fragment_friend, null);
    ListView friendList = (ListView) inflatedView.findViewById(R.id.friend_listView);
    friendList.setAdapter(friendAdaptor);

Below code the database and listView works, but my navbar drawer is gone and i when i try to get back to activity_main, app crashes 下面的代码数据库和listView工作,但我的导航栏抽屉不见了,当我尝试回到activity_main时,应用崩溃

Try 2 code 尝试2个代码

    setContentView(R.layout.fragment_friend);
    ListView friendList = (ListView) inflatedView.findViewById(R.id.friend_listView);
    friendList.setAdapter(friendAdaptor);

app_bar_main.xml app_bar_main.xml

    <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_main" />-->
    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"/>

    <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" />

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

I believe the root of your problem comes down to a lack of familiarity with the general Android Fragment APIs. 我认为,问题的根源归结于对通用Android Fragment API的缺乏了解。 That's fine; 没关系; everyone is new when they start. 每个人开始时都是新来的。 But it means that your question is quite difficult to answer concisely (beyond "read about Fragments"). 但这意味着您的问题很难简洁地回答(除了“阅读有关片段的信息”)。

You should, of course, start by reading about Fragments: https://developer.android.com/guide/components/fragments.html 当然,您应该先阅读有关片段的信息: https : //developer.android.com/guide/components/fragments.html

Still, I think we can cover things here in brief. 不过,我认为我们可以在这里简单介绍一下。

All Fragments must be hosted in an Activity. 所有片段都必须托管在活动中。 The normal way to do this is either by adding a <fragment> tag to your activity's xml layout, or by including a <FrameLayout> in your activity's xml layout and then using a FragmentTransaction to dynamically add/replace/remove fragments from that frame. 通常的方法是在活动的xml布局中添加<fragment>标记,或者在活动的xml布局中包含<FrameLayout> ,然后使用FragmentTransaction从该框架中动态添加/替换/删除片段。

In your posted code, inside app_bar_main.xml , I see this: 在您发布的代码中,在app_bar_main.xml ,我看到了:

<FrameLayout
    android:id="@+id/flContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"/>

This is clearly the place where your fragments will eventually live, but you'll have to add them to the frame yourself in your Java code. 显然,这是片段最终将存在的地方,但是您必须自己在Java代码中将它们添加到框架中。 You actually have a method that does this already: 实际上,您已经有一种方法可以执行此操作:

private void displaySelectedScreen(int id){
    Fragment fragment = ...

    if(fragment != null){
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.flContent, fragment);
        ft.commit();
    }

    ...
}

It looks like this is meant to be used when your user clicks on an item in your navigation drawer, but the concept is the same. 当用户单击导航抽屉中的某个项目时,看起来应该使用它,但是概念是相同的。 If you want your app to always start up with the "friends" fragment displayed, you can add this code to your activity's onCreate() method: 如果希望您的应用始终以显示的“ friends”片段启动,则可以将此代码添加到活动的onCreate()方法中:

if (savedInstanceState == null) {
    getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.flContent, new friend())
        .commit();
}

Now you will have a friend fragment to work with! 现在,您将可以使用一个friend片段!

However, fragment transactions aren't guaranteed to be executed right away, so even though (as a user) you'll always see this friend fragment when the app starts up, you won't necessarily be able to interact with it (as a programmer) immediately after writing this code. 但是,不能保证碎片交易会立即执行,因此即使(作为用户)您始终会在应用启动时看到此friend碎片,但不一定能与之交互(作为用户程序员)。 So you'll also have to move your call to populateFriendList() from your onCreate() method. 因此,您还必须将调用从onCreate()方法移至populateFriendList()

Instead, you should populate the friends list from within the friend fragment itself! 相反,您应该从friend片段本身中填充朋友列表! Probably the right place to do this is inside the onActivityCreated() method of your fragment. 大概合适的位置是片段的onActivityCreated()方法内。

To find a view from inside a Fragment subclass, you can't just write findViewById() the way you can in an Activity . 要从Fragment子类内部查找视图,您不能像在Activity那样直接编写findViewById() However, you can write this instead: getView().findViewById() ... as long as you're doing this after your onCreateView() method has returned. 但是,您可以编写以下代码: getView().findViewById() ...,只要在返回onCreateView()方法之后执行此操作即可。

Anyway, this answer is getting extremely long even as I try to keep it as short as possible. 无论如何,即使我尝试使答案尽可能短,该答案也变得越来越长。 I hope this is enough information for you to get your app up and running. 我希望这是足够的信息,可让您启动和运行您的应用程序。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM