Android静态片段-应用崩溃问题

时间:2018-10-16 03:36:02

标签: java android android-fragments

我是一名Android初学者,只是学习android静态片段概念,但是在运行我的代码后出现应用崩溃的问题。这是详细信息:

MainActivity.java

package com.example.lalendrakumar.fragmentdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

activity_main.xml

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:weightSum="2">

<fragment
    android:id="@+id/fragment1"

    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1" />
<fragment
    android:id="@+id/fragment2"


    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1" />

任何人都可以解决我的问题。

3 个答案:

答案 0 :(得分:0)

我假设您希望这两个片段填充整个页面。 “ fill_parent”现已替换为“ match_parent”。但是,从理论上讲,如果使用此片段,则两个片段将彼此重叠。

要在屏幕上拆分它们,必须将每个元素的高度调整为零。这就是每个片段的尺寸应读取的方式

android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"

答案 1 :(得分:0)

您没有提到正在使用哪种布局,但是我想您正在使用LinearLayout。默认情况下,LinearLayout的水平方向是水平的,并且您给了match_parent高度和宽度(不建议使用fill_parent并由match_parent代替)

请在此link

上找到有关LinearLayout的更多信息

使用以下代码替换您的代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<fragment
    android:id="@+id/fragment1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />
<fragment
    android:id="@+id/fragment2"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />

答案 2 :(得分:0)

尝试注释掉片段类中的这些行(如果存在的话)

     /*  @Override
       public void onAttach(Context context) {
       if (context instanceof OnFragmentInteractionListener) {
          mListener = (OnFragmentInteractionListener) context;
      } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
      }
   }
 */