移动布局 - 现在findViewByID无法使用它

时间:2015-09-01 08:00:48

标签: android xml android-layout android-fragments

我决定使用片段作为活动的替代方法,因此我将activity_main.xml剪切为2个不同的XML文件:activity_main.xml和fragment_main.xml。问题是我之前在java中引用的activity_main中的relativeLayout在我将其移动到另一个XML文件后不再有效。看起来你需要设置你正在使用的任何XML文件的内容视图来查找ViewByID,但是用条形图数据填充我的图表可能需要两者;需要将fragment_main.xml设置为我的内容视图(这是我用其他片段填充的空白),并且需要设置activity_main以将其显示为我的主屏幕的一部分。 fSetGraph();正在使用此图表:https://github.com/PhilJay/MPAndroidChart

出于好奇:在这里的任何地方布局都会发挥作用吗?

MainActivity.java

        public class MainActivity extends AppCompatActivity {

            private DrawerLayout mDrawer;
            private Toolbar toolbar;
            private RecyclerView recyclerView;
            private NavigationView nvDrawer;
            FloatingActionButton fab;
            FragmentManager manager = getSupportFragmentManager();

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

                setContentView(R.layout.fragment_main);
                fSetGraph();
                fsetFAB();

        //        setContentView(R.layout.activity_main);
        //        fSetToolBar();
        //        fSetDrawer();
        //        fSetDrawerContent();
        //        fsetInitialFragment();


            }


    private void fSetGraph() {
.
.  //Lots of code here about setting the graph. Not important.
.


    RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayoutForChart);
    rl.addView(MainActivity.barChartGlobal,
                    new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));

    }

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/linearLayoutMainActivity"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


            <!-- The ActionBar -->
            <include
                layout="@layout/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>





            <RelativeLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/relativeLayoutActivity"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:background="#FFFFFF">




                <!--Fragments placed here-->





            </RelativeLayout>

        </LinearLayout>

        <!-- The navigation drawer -->
        <android.support.design.widget.NavigationView
            android:id="@+id/nvView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@android:color/white"
            app:menu="@menu/drawer_view"
            app:headerLayout="@layout/drawer_header">

            <!--<include-->
            <!--layout="@layout/drawer_header"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="160dp"/>-->

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





    </android.support.v4.widget.DrawerLayout>

fragment_main.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <!-- Here on down is the fragment I'm using in activity_main.xml-->


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="false"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:id="@+id/relativeLayoutForChart"
        android:layout_above="@+id/linearLayoutForCenterReference"
        android:layout_below="@+id/linearLayoutHeader">


        <com.github.mikephil.charting.charts.BarChart
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/chart"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_gravity="center"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="false" />




    </RelativeLayout>


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/linearLayoutForCenterReference">
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayoutLabels"
        android:gravity="center_vertical|center_horizontal"
        android:layout_alignTop="@+id/linearLayoutForCenterReference"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="false"
        android:layout_centerHorizontal="true"
        android:layout_toRightOf="@+id/relativeLayoutSchedule"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="tv1"
            android:id="@+id/textView1"
            android:textSize="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="tv2"
            android:id="@+id/textView2"
            android:textSize="15dp"
            android:layout_marginLeft="52dp"
            android:layout_marginRight="52dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="tv3"
            android:id="@+id/textView3"
            android:textSize="15dp" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:id="@+id/linearLayoutHeader"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:gravity="center_horizontal">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="One"
                android:id="@+id/textViewOne"
                android:layout_alignParentTop="true"
                android:layout_toLeftOf="@+id/textViewState"
                android:layout_toStartOf="@+id/textViewState" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Two"
                android:id="@+id/textViewTwo"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="50dp"
                android:layout_marginRight="40dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Three"
                android:id="@+id/textViewThree"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/textViewState"
                android:layout_toEndOf="@+id/textViewState" />
        </RelativeLayout>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayoutLabels"
        android:layout_centerHorizontal="true"
        android:id="@+id/linearLayoutActivityFeed"
        android:gravity="center_vertical|center_horizontal"
        android:paddingTop="0dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="3dp">

        <ImageView
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/imageView2"
            android:src="@drawable/ic_assignment_black_24dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Activity Feed"
            android:id="@+id/textViewActivityFeed"
            android:layout_marginBottom="1dp" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/linearLayoutActivityFeed"
        android:layout_centerHorizontal="true"
        android:id="@+id/relativeLayoutForTabs">









        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            android:gravity="right">



            <android.support.design.widget.TabLayout
                android:id="@+id/sliding_tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways"/>



            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="0px"
                android:layout_weight="1"
                android:background="@android:color/white">






            </android.support.v4.view.ViewPager>





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

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_add_black_24dp"
            android:layout_marginBottom="20dp"
            android:layout_marginRight="20dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/drawer_recyclerView"
            android:layout_width="match_parent"
            android:layout_gravity="start"
            android:layout_height="match_parent"
            android:background="#FFFFFF">

        </android.support.v7.widget.RecyclerView>


    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayoutForCenterReference"
        android:layout_above="@+id/linearLayoutActivityFeed"
        android:layout_alignParentStart="false"
        android:layout_alignParentEnd="false"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="false"
        android:id="@+id/relativeLayoutSchedule"
        android:layout_alignParentTop="false"
        android:gravity="center_vertical"
        android:layout_alignTop="@+id/linearLayoutLabels"
        android:layout_marginLeft="15dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageViewSchedule"
            android:src="@drawable/ic_event_black_24dp"
            android:contentDescription="Event Icon" />
    </RelativeLayout>



</RelativeLayout>

尝试运行fSetGraph()的结尾部分,并将contentView设置为activity_main而不是fragment_main(图表所在的)给出了错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{...MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.addView(android.view.View, android.view.ViewGroup$LayoutParams)' on a null object reference

导航抽屉代码

    switch (menuItem.getItemId()) {
            case R.id.navigation_item_log_in:

                DialogPopupSignInFragment alertDialogSignInCustom = new DialogPopupSignInFragment();
                alertDialogSignInCustom.show(manager, "DialogSignIn");

                break;

            case R.id.navigation_item_home:


                FragmentMain fragmentMain = new FragmentMain();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.relativeLayoutActivity, fragmentMain, "Home");
                transaction.commit();

                setTitle("App Home");


                break;

            case R.id.my_stats:

                FragmentMyStats fragmentMyStats = new FragmentMyStats();
                FragmentTransaction transactionMyStats = manager.beginTransaction();
                transactionMyStats.replace(R.id.relativeLayoutActivity, fragmentMyStats , "MyStats");
                transactionMyStats.commit();

                setTitle("My Stats");

                break;

            case R.id.navigation_item_winners:

                FragmentWinners fragmentWinners = new FragmentWinners();
                FragmentTransaction transactionWinners = manager.beginTransaction();
                transactionWinners.replace(R.id.relativeLayoutActivity, fragmentWinners, "Winners");
                transactionWinners.commit();

                setTitle("Winners");

                break;

            case R.id.navigation_item_settings:

                FragmentSettings fragmentSettings = new FragmentSettings();
                FragmentTransaction transactionSettings = manager.beginTransaction();
                transactionSettings.replace(R.id.relativeLayoutActivity, fragmentSettings, "Settings");
                transactionSettings.commit();

                setTitle("Settings");

                break;

            case R.id.navigation_item_about:

                FragmentAbout fragmentAbout = new FragmentAbout();
                FragmentTransaction transactionAbout = manager.beginTransaction();
                transactionAbout.replace(R.id.relativeLayoutActivity, fragmentAbout, "About");
                transactionAbout.commit();

                setTitle("About");

                break;

        }

在MainActivity中设置抽屉

private void fSetDrawer() {
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.app_name, R.string.app_name);
        mDrawer.setDrawerListener(drawerToggle);
        drawerToggle.syncState();
    }

来自activity_main的导航抽屉XML

<android.support.design.widget.NavigationView
            android:id="@+id/nvView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@android:color/white"
            app:menu="@menu/drawer_view"
            app:headerLayout="@layout/drawer_header">

            <!--<include-->
            <!--layout="@layout/drawer_header"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="160dp"/>-->

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

导航抽屉菜单

<group
        android:checkableBehavior="single">

        <item
            android:id="@+id/navigation_item_log_in"
            android:icon="@drawable/ic_person_black_24dp"
            android:title="Log In">
        </item>

        <item
            android:id="@+id/navigation_item_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="Home">
        </item>

        <item
            android:id="@+id/my_stats"
            android:icon="@drawable/ic_developer_board_black_24dp"
            android:title="My Stats">
        </item>

        <item
            android:id="@+id/navigation_item_winners"
            android:icon="@drawable/ic_wb_iridescent_black_24dp"
            android:title="Winners">
        </item>

        <item
            android:id="@+id/navigation_item_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="Settings">
        </item>

        <item
            android:id="@+id/navigation_item_about"
            android:icon="@drawable/ic_local_library_black_24dp"
            android:title="About">
        </item>

        <!--Recycler View-->





    </group>

1 个答案:

答案 0 :(得分:1)

是的,它与布局inflaters有关。发生的事情是当你使用findViewById时,活动只检查setContectView中的布局,在你的情况下是activity_main。因此,活动无法找到r1。对此的解决方案是在片段中膨胀r1,然后通过主要活动引用它。

import android.support.v4.app.Fragment; //Edit : make sure its this

public class MapFragment extends Fragment{ 

View v //EDIT

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

 RelativeLayout rl = (RelativeLayout) v.findViewById(R.id.relativeLayoutForChart); //EDIT
rl.addView(barchart,
                new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
        return v;

}

在其中创建一个新类。然后在您的主要活动中输入此代码

FragmentTransaction ft = ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction();
MapFragment mapFragment=new MapFragment();
ft.replace(R.id.fragment_map, placeOrderFragment).addToBackStack(null).commit();

在main_activity xml中,添加一个id为map_fragment。

基本上流将是你的地图将被放入片段xml中,然后由片段类膨胀,然后由主活动使用。

编辑:调整代码。看看吧。当布局膨胀时,要在该布局中查找视图组,它必须与findViewById一起传递,因此需要进行小的更改。此外,在定义片段时,请确保导入v4。一个向后兼容。