在android中动态添加片段到主要活动的问题,请看我的代码

时间:2014-03-27 16:21:03

标签: java android xml android-fragments

我现在正在学习片段,并编写一个简单的项目希望通过java代码将fragment添加到MainActivity。但不要将xml插入main_activity.xml

但是在我完成代码之后,它无法在设备上运行,只是警告"应用程序停止运行"。

这是我的代码:

  1. MainActivity.java

    package com.example.dynamicfragment;
    
    import android.os.Bundle;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.view.Menu;
    
    public class MainActivity extends Activity {
    
    
    @SuppressLint("NewApi")
    @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    
    ButtonList buttonlist_fragment = new ButtonList(); // instanciate a new view of ButtonList
    
    FragmentManager fragment_manager= getFragmentManager(); //fragment manager and fragment transaction
    FragmentTransaction fragment_transaction = fragment_manager.beginTransaction();     
    fragment_transaction.add(R.id.layoutToReplace, buttonlist_fragment);
    fragment_transaction.commit();
    }
    
       }
    
  2. activity_main.xml中

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".MainActivity" >
    
    <LinearLayout 
    android:id="@+id/layoutToReplace"
    android:orientation="vertical">
    
    </LinearLayout>
    </RelativeLayout>
    
  3. 片段类:

     @SuppressLint("NewApi")
     public class ButtonList extends Fragment {
    
     public View onCreateView(LayoutInflater inflater, ViewGroup Container, Bundle savedInstanceState){
    
    //return inflate layout for this fragment
    return inflater.inflate(R.layout.button_list_fragment_layout, Container,false);
    
       } 
       } 
    
  4. 片段XML布局:

      <?xml version="1.0" encoding="UTF-8"?>
      <Linerlayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
       android:layout_height="fill_parent"
      >
    
      <Button
      android:id="@+id/Student"
      android:layout_width="150dip"
      android:layout_height="wrap_content"
      android:layout_marginTop="50dip"
      android:text="Student"
      />
      <Button
      android:id="@+id/Documents"
      android:layout_width="150dip"
      android:layout_height="wrap_content"
      android:text="Documents"
      />
      </Linerlayout>
    
  5. log cat

    03-27 12:22:21.913: D/AndroidRuntime(23764): Shutting down VM
    03-27 12:22:21.913: W/dalvikvm(23764): threadid=1: thread exiting with uncaught exception (group=0x40b2c1f8)
    03-27 12:22:21.976: E/AndroidRuntime(23764): FATAL EXCEPTION: main
    03-27 12:22:21.976: E/AndroidRuntime(23764): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dynamicfragment/com.example.dynamicfragment.MainActivity}: java.lang.RuntimeException: Binary XML file line #11: You must supply a layout_width attribute.
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.os.Handler.dispatchMessage(Handler.java:99)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.os.Looper.loop(Looper.java:137)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.main(ActivityThread.java:4499)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at java.lang.reflect.Method.invokeNative(Native Method)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at java.lang.reflect.Method.invoke(Method.java:511)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at dalvik.system.NativeStart.main(Native Method)
    03-27 12:22:21.976: E/AndroidRuntime(23764): Caused by: java.lang.RuntimeException: Binary XML file line #11: You must supply a layout_width attribute.
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:491)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:5318)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:5439)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.widget.RelativeLayout$LayoutParams.<init>(RelativeLayout.java:1154)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.widget.RelativeLayout.generateLayoutParams(RelativeLayout.java:1021)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.widget.RelativeLayout.generateLayoutParams(RelativeLayout.java:72)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:741)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:262)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.Activity.setContentView(Activity.java:2007)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.example.dynamicfragment.MainActivity.onCreate(MainActivity.java:18)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.Activity.performCreate(Activity.java:4637)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
    03-27 12:22:21.976: E/AndroidRuntime(23764):    ... 11 more
    03-27 12:22:25.929: I/Process(23764): Sending signal. PID: 23764 SIG: 9
    

3 个答案:

答案 0 :(得分:0)

您的“主要活动xml布局”包含LinearLayout标记,没有必要的属性 - layout_widthlayout_height

将它们设置为match_parent或其他:

<RelativeLayout ... >

<LinearLayout 
    android:id="@+id/layoutToReplace"
    android:orientation="vertical"

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

奇怪的是,您为MainActivity提供了这样的布局,考虑到它将托管Fragment。通常,FrameLayout用于此目的。 Consider reading this

答案 1 :(得分:0)

您需要指定LinearLayout的布局宽度和高度。

但是查看activity_main.xmlRelativeLayoutLinearLayout都不需要。您可以将其中任何一个(LinaerLayout / RelativeLayout)用作ViewGroup。通常使用FrameLayout

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/layoutToReplace"
    android:layout_height="match_parent" >

</FrameLayout>

其次你有@SuppressLint("NewApi")。 lint工具提示您某些功能仅在新api中可用,您需要检查清单文件以获取min sdk版本以检查兼容性。

我猜你的min sdk低于api等级11.检查清单

第三,不推荐fill_parent使用match_parent

引用文档

  

fill_parent(在API级别8中重命名为match_parent)告诉您的视图   变得像其父视图组一样大。

<Linerlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

答案 2 :(得分:0)

#2和#4是什么意思? 它给你的LogCat错误是什么?

错误在哪一行?

JAVA = MainActivity =

    onCreate () {
setContentView(R.layout.frag_vocablist); 
    }

    public void onItemSelected(String id) {
    Bundle arguments = new Bundle();
    arguments.putString(“FragmentB_package”, id);


    FragmentB fragment = new FragmentB();
    fragment.setArguments(arguments);
    getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
}

R.layout.frag_vocablist。在您的MainActivity.java的XML布局中包括=

   <fragment
        android:id="@+id/vocab_list"
        android:name="com.gene.yourPackageName.Frag_JavaClass"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@android:layout/list_content" />

机器人:名称=&#34; com.gene.yourPackageName.Frag_JavaClass&#34;调用Java文件Frag_JavaClass。在Frag_JavaClass里面你需要设置:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
        if (savedInstanceState != null
                && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
            setActivatedPosition(savedInstanceState
                    .getInt(STATE_ACTIVATED_POSITION));
        }
        mView = inflater.inflate(R.layout.frag_abc_sort, container, false);
        mABCListView = (IndexableListView) mView.findViewById(R.id.frag_abc);
        //...
        return mView;
    }

    public void replaceFrag(String[] List, boolean SetABCListScrollable) {
        mABCListView.setFastScrollEnabled(true);
        mABCListView.showList(SetABCListScrollable);
        ContentAdapter adapter = new ContentAdapter(mView.getContext(),
                android.R.layout.simple_list_item_1, List);
        mABCListView.setAdapter(adapter);
    }

R.layout.frag_abc_sort = Frag_JavaClass.java的XML布局

<com.gene.android.Frag_JavaClass.IndexableListView
    android:id="@+id/frag_abc"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" />

如果您仍然无法获取,请在此处查看我的评论: How to pass data between fragments