2017-09-01 135 views
-2

T'm尝试一个非常简单的事情。通过java代码添加一个片段。但它显示我错误(fragmentTransaction.add(R.id.fragment_container,fragment);)。我无法理解这里有什么问题。请帮忙。有两个类,主类和片段类。两种布局主要布局和片段布局。将片段添加到Android

<?xml version="1.0" encoding="utf-8"?> 
<android.support.constraint.ConstraintLayout 
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" 
tools:context="com.example.chetan.fragmentprtc.MainActivity"> 


<fragment 
    android:id="@+id/fragment_container" 
    android:name="android.app.DialogFragment" 
    android:layout_width="368dp" 
    android:layout_height="495dp" 
    tools:layout_editor_absoluteX="8dp" 
    tools:layout_editor_absoluteY="8dp" /> 

</android.support.constraint.ConstraintLayout> 


package com.example.chetan.fragmentprtc; 
import android.app.FragmentManager; 
import android.app.FragmentTransaction; 
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); 

    FragmentManager fragmentManager = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = 
fragmentManager.beginTransaction(); 
    BlankFragment fragment = new BlankFragment(); 
    fragmentTransaction.add(R.id.fragment_container, fragment); 
    fragmentTransaction.commit(); 
} 
} 




<FrameLayout 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" 
tools:context="com.example.chetan.fragmentprtc.BlankFragment"> 

<!-- TODO: Update blank fragment layout --> 
<TextView 
    android:id="@+id/fragment1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:text="@string/hello_blank_fragment" /> 

</FrameLayout> 

package com.example.chetan.fragmentprtc; 


import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

public class BlankFragment extends Fragment { 


public BlankFragment() { 
    // Required empty public constructor 
} 


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

} 

} 

回答

0

抬起头来!

处理碎片的一个重要规则是您的activity布局必须包含一个容器视图,您可以在其中插入片段。

容器可以是ViewGroup,如FrameLayoutLinearLayout。在你的情况下,你正在替换Fragment中的一个片段 - 这是出错的地方。

使用下面的代码作为容器 -

<FrameLayout 
    android:id="@+id/fragment_container" 
    .... 
    ... /> 
+0

你好精灵!我已经更改了xlm文件中的代码。但是有一行错误:transaction.replace(R.id.fragment_container,fragment); –

0

首先你要记住一两件事: 片段在XML硬编码的,无法替代的。 并且您的代码似乎存在多个问题。首先是MainActivity的布局,另一件事是根据需要替换而不是添加片段。那么简单的方法,我已经重构你的代码如下:

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

<FrameLayout 
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:id="@+id/fragment_container" 
android:name="android.app.DialogFragment" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context="com.example.chetan.fragmentprtc.MainActivity" 
/> 

您的MainActivity代码:

package com.example.chetan.fragmentprtc; 
import android.app.FragmentManager; 
import android.app.FragmentTransaction; 
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); 

    FragmentTransaction transaction = 
getFragmentManager().beginTransaction(); 
BlankFragment fragment = new BlankFragment(); 
transaction.replace(R.id.fragment_container, fragment); 
transaction.addToBackStack(null); 

transaction.commit(); 


} 
} 

而孩子片段的布局为:

<LinearLayout 
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" 
tools:context="com.example.chetan.fragmentprtc.BlankFragment"> 

<TextView 
android:id="@+id/fragment1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:gravity="center" 
android:text="@string/hello_blank_fragment" /> 

</LinearLayout> 

希望它会在重构这些之后进行工作。

+0

嗨Krantiz,谢谢你的帮助。我用你的代码,但它仍然显示行中的错误:transaction.replace(R.id.fragment_container,fragment); –

1

我不知道为什么上面的代码不适合我。但是这样做:

BlankFragment firstFragment = new BlankFragment(); 
getSupportFragmentManager().beginTransaction() 
       .add(R.id.fragment_container, firstFragment).commit(); 

这不显示任何错误,它确实工作!谢谢你们。

+0

我正在建议这种方法,我很高兴你发布了解决方案。我相信因为你的活动扩展了'AppCompatActivity',你需要在适用的时候使用支持库来完成向后兼容的正确实现。 – DMP

-1

示例片段

fragment_home.xml

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

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:background="#ecf1f4" 
     android:layout_marginBottom="10dp"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="vertical" 
      android:background="#ecf1f4"> 

      <android.support.v4.view.ViewPager 
       android:id="@+id/viewPager2" 
       android:layout_width="match_parent" 
       android:layout_height="150dp"/> 

      <LinearLayout 
       android:id="@+id/SliderDots" 
       android:layout_below="@+id/viewPager2" 
       android:orientation="horizontal" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:background="#00000000" 
       android:layout_marginTop="10dp" 
       android:layout_marginStart="10dp"/> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:background="#ecf1f4"> 

      <TextView 
       android:id="@+id/tvHotPromo" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Message" 
       android:layout_marginStart="10dp" 
       android:layout_marginTop="15dp" 
       android:textSize="18sp" 
       android:textStyle="bold" 
       android:textColor="@color/colorSc2"/> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="fill_parent" 
      android:layout_height="120dp" 
      android:orientation="horizontal" 
      android:layout_weight="1"> 

      <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_weight="1"> 
       <android.support.v7.widget.CardView 
        xmlns:card_view="http://schemas.android.com/apk/res-auto" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        card_view:cardCornerRadius="3dp" 
        card_view:cardElevation="3dp" 
        card_view:cardBackgroundColor="#fff" 
        android:clickable="true" 
        android:foreground="?android:attr/selectableItemBackground" 
        card_view:cardUseCompatPadding="true" 
        android:onClick="semuaProduk"> 

        <LinearLayout 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" 
         android:orientation="vertical" 
         android:layout_gravity="center"> 

         <ImageView 
          android:layout_width="40dip" 
          android:layout_height="40dip" 
          android:layout_gravity="center" 
          android:src="@drawable/ic_semua_2" /> 

         <TextView 
          android:layout_width="match_parent" 
          android:layout_height="match_parent" 
          android:fontFamily="sans-serif-medium" 
          android:text="Message" 
          android:paddingTop="10dp" 
          android:textAlignment="center" 
          android:textColor="#2e2e2e" 
          android:textSize="12sp" /> 

        </LinearLayout> 

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

      </LinearLayout> 
      <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_weight="1"> 
       <android.support.v7.widget.CardView 
        xmlns:card_view="http://schemas.android.com/apk/res-auto" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        card_view:cardCornerRadius="3dp" 
        card_view:cardElevation="3dp" 
        card_view:cardBackgroundColor="#fff" 
        android:clickable="true" 
        android:foreground="?android:attr/selectableItemBackground" 
        card_view:cardUseCompatPadding="true" 
        android:onClick="makanan"> 

        <LinearLayout 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="vertical" 
         android:layout_gravity="center"> 

         <ImageView 
          android:layout_width="40dip" 
          android:layout_height="40dip" 
          android:src="@drawable/ic_makanan_2" 
          android:layout_gravity="center"/> 

         <TextView 
          android:layout_width="match_parent" 
          android:layout_height="match_parent" 
          android:fontFamily="sans-serif-medium" 
          android:paddingTop="10dp" 
          android:text="Message" 
          android:textAlignment="center" 
          android:textColor="#2e2e2e" 
          android:textSize="12sp" /> 
        </LinearLayout> 

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

      </LinearLayout> 
      <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_weight="1"> 
       <android.support.v7.widget.CardView 
        xmlns:card_view="http://schemas.android.com/apk/res-auto" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        card_view:cardCornerRadius="3dp" 
        card_view:cardElevation="3dp" 
        card_view:cardBackgroundColor="#fff" 
        android:clickable="true" 
        android:foreground="?android:attr/selectableItemBackground" 
        card_view:cardUseCompatPadding="true" 
        android:onClick="minum"> 

        <LinearLayout 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="vertical" 
         android:layout_gravity="center"> 

         <ImageView 
          android:layout_width="40dip" 
          android:layout_height="40dip" 
          android:layout_gravity="center" 
          android:src="@drawable/ic_minum"/> 

         <TextView 
          android:layout_width="match_parent" 
          android:layout_height="match_parent" 
          android:fontFamily="sans-serif-medium" 
          android:paddingTop="10dp" 
          android:text="Message" 
          android:textAlignment="center" 
          android:textColor="#2e2e2e" 
          android:textSize="12sp" /> 

        </LinearLayout> 
       </android.support.v7.widget.CardView> 

      </LinearLayout> 
      <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_weight="1"> 
       <android.support.v7.widget.CardView 
        xmlns:card_view="http://schemas.android.com/apk/res-auto" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        card_view:cardCornerRadius="3dp" 
        card_view:cardElevation="3dp" 
        card_view:cardBackgroundColor="#fff" 
        android:clickable="true" 
        android:foreground="?android:attr/selectableItemBackground" 
        card_view:cardUseCompatPadding="true" 
        android:onClick="oleh2"> 

        <LinearLayout 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" 
         android:orientation="vertical" 
         android:layout_gravity="center"> 

         <ImageView 
          android:layout_width="40dip" 
          android:layout_height="40dip" 
          android:layout_gravity="center" 
          android:src="@drawable/ic_oleh2" /> 

         <TextView 
          android:layout_width="match_parent" 
          android:layout_height="match_parent" 
          android:fontFamily="sans-serif-medium" 
          android:text="Message" 
          android:paddingTop="10dp" 
          android:textAlignment="center" 
          android:textColor="#2e2e2e" 
          android:textSize="12sp" /> 

        </LinearLayout> 

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

      </LinearLayout> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:background="#ecf1f4" 
      android:orientation="vertical" 
      android:id="@+id/llDaftarHome"> 

      <android.support.v7.widget.CardView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:background="#fff" 
       android:elevation="5dp" 
       android:layout_marginStart="5dp" 
       android:layout_marginEnd="5dp" 
       android:layout_marginTop="5dp" 
       android:layout_marginBottom="5dp"> 

       <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:orientation="vertical"> 

        <Button 
         android:layout_width="match_parent" 
         android:layout_height="40dp" 
         android:text="Message" 
         android:background="@drawable/rounded_button_daftar" 
         android:textColor="#fff" 
         android:textSize="18sp" 
         android:elevation="5dp" 
         android:layout_marginStart="20dp" 
         android:layout_marginEnd="20dp" 
         android:layout_marginTop="20dp" 
         android:layout_marginBottom="20dp" 
         android:onClick="daftar"/> 
        <TextView 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:textColor="@color/colorSc2" 
         android:textSize="14sp" 
         android:layout_marginStart="20dp" 
         android:layout_marginTop="-10dp" 
         android:layout_marginBottom="10dp" 
         android:text="Message"/> 

       </LinearLayout> 

      </android.support.v7.widget.CardView> 
     </LinearLayout> 

    </LinearLayout> 

</ScrollView> 

HomeFragment.java

public class UtamaFragment extends Fragment { 

    private static final String Database_Path = "p_db/banner"; 
    private DatabaseReference databaseReference; 
    ViewPagerAdapter viewPagerAdapter; 

    public static ViewPager viewPager; 
    private LinearLayout sliderDotspanel; 
    private ImageView[] dots; 
    private int dotscount; 

    private LinearLayout llDaftarHome; 
    private LinearLayout llPb; 

    public UtamaFragment() { 
    } 

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

    } 

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

     viewPager = (ViewPager)rootView.findViewById(R.id.viewPager2); 
     sliderDotspanel = (LinearLayout)rootView.findViewById(R.id.SliderDots); 
     viewPagerAdapter = new ViewPagerAdapter(getContext()); 

     databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path); 
     databaseReference.orderByChild("link").addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       int i = 0; 
       for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { 
        try { 
         Banner banner = postSnapshot.getValue(Banner.class); 
         viewPagerAdapter.setImage(banner.getLink(), i); 
         i++; 
        }catch (Exception e){ 
         e.printStackTrace(); 
        } 
       } 

       viewPagerAdapter.setFullscreen(false); 
       viewPager.setAdapter(viewPagerAdapter); 
       viewPagerAdapter.notifyDataSetChanged(); 

       dotscount = viewPagerAdapter.getCount(); 
       dots = new ImageView[dotscount]; 

       for (int j = 0; j < dotscount; j++) { 

        dots[j] = new ImageView(getContext()); 
        dots[j].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.nonactive_dot_home)); 

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 

        params.setMargins(8, 0, 8, 0); 
        sliderDotspanel.addView(dots[j], params); 
       } 

       dots[0].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot_home)); 

       viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
        @Override 
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 

        } 

        @Override 
        public void onPageSelected(int position) { 

         for (int i = 0; i < dotscount; i++) { 
          dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.nonactive_dot_home)); 
         } 

         dots[position].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot_home)); 
        } 

        @Override 
        public void onPageScrollStateChanged(int state) { 

        } 
       }); 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 

      } 
     }); 

     llDaftarHome = (LinearLayout)rootView.findViewById(R.id.llDaftarHome); 
     if(FirebaseAuth.getInstance().getCurrentUser() != null){ 
      llDaftarHome.setVisibility(View.GONE); 
     } 

     return rootView; 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
    } 

    @Override 
    public void onDetach() { 
     super.onDetach(); 
    } 

} 
+1

尽管此代码可能会回答这个问题,但提供有关为什么和/或代码如何回答问题的其他上下文会提高其长期价值。 – rollstuhlfahrer