2017-09-01 3 views
-2

T'm versucht eine sehr einfache Sache. Fügen Sie ein Fragment über Java-Code hinzu. Aber es zeigt mir Fehler in (fragmentTransaction.add (R.id.fragment_container, Fragment);). Ich kann nicht verstehen, was hier falsch ist. Bitte helfen Sie. Es gibt zwei Klassen, die Hauptklasse und die Fragmentklasse. und zwei Layouts das Hauptlayout und das Fragmentlayout.Hinzufügen von Fragment zu 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; 

} 

} 

Antwort

0

Kopf hoch !!

Eine wichtige Regel beim Umgang mit Fragmenten ist, dass Ihr activity Layout eine Containeransicht enthalten muss, in die Sie das Fragment einfügen können.

Container kann eine ViewGroup wie FrameLayout oder LinearLayout sein. In Ihrem Fall ersetzen Sie ein Fragment in der Fragment - das ist, wo Dinge falsch gelaufen sind.

den Code unten als Container verwenden -

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

Hallo Wizard! Ich habe den Code in der XLM-Datei geändert. Aber es gibt einen Fehler in Zeile: transaction.replace (R.id.fragment_container, Fragment); –

0

Zuerst Sie eine Sache erinnern müssen: Fragmente, die in XML hart codiert sind, können nicht ersetzt werden. und es scheint mehr als ein Problem mit Ihrem Code zu geben. Die erste Sache ist das Layout von MainActivity und eine andere Sache nach Ihrem Bedarf, die Sie ersetzen müssen, anstatt Fragment hinzuzufügen. Nun, in einfacher Weise ich Ihren Code wie folgt Refactoring haben:

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

Ihr MainActivity Code:

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(); 


} 
} 

und das Layout des Kindes Fragment als:

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

es hoffen, arbeite nach dem Refactoring so viel.

+0

Hallo Krantiz, Danke für die Hilfe. Ich habe Ihren Code verwendet, aber es zeigt immer noch Fehler in Zeile: transaction.replace (R.id.fragment_container, Fragment); –

1

Ich weiß nicht, warum der obige Code für mich nicht funktioniert. aber dies tat:

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

Dies ist kein Fehler zeigt, und es funktionierte! Danke euch allen.

+0

Ich wollte diesen Ansatz vorschlagen und ich bin froh, dass Sie die Lösung gepostet haben. Ich glaube, da Ihre Aktivität "AppCompatActivity" erweitert, müssen Sie ggf. Support-Bibliotheken verwenden, um die korrekte Implementierung der Abwärtskompatibilität zu erreichen. – DMP

-1

Beispiel Fragment

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

Während dieser Code die Frage beantworten kann, verbessert ein zusätzlicher Kontext, warum und/oder wie dieser Code die Frage beantwortet, seinen langfristigen Wert. – rollstuhlfahrer

Verwandte Themen