2016-05-26 18 views
0

Ich habe zwei Fragmente (layout_first.xml und layout_second.xml).
Ich möchte dies tun: Klicken Sie auf eine Schaltfläche (Show Second) im ersten Fragment, um das zweite Fragment anzuzeigen und einen EditText-Wert im ersten Fragment zu erhalten, um den EditText-Wert im zweiten Fragment programmatisch zu setzen.Wie kann ich programmatisch zu einem anderen Fragment wechseln?

Hier ist mein Code:

activity_main.xml

<android.support.design.widget.CoordinatorLayout 
    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"> 
    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:layout_scrollFlags="scroll|enterAlways" 
      app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> 

     <android.support.design.widget.TabLayout 
      android:id="@+id/tabs" 
      android:layout_width="match_parent" 
      android:layout_height="@dimen/custom_tab_layout_height" 
      app:tabMode="fixed" 
      app:tabGravity="fill"/> 
    </android.support.design.widget.AppBarLayout> 
    <android.support.v4.view.ViewPager 
     android:id="@+id/viewpager" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     xmlns:ads="http://schemas.android.com/apk/res-auto" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior" /> 
</android.support.design.widget.CoordinatorLayout> 

layout_first.xml

<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" 
    android:orientation="horizontal" 
    android:focusable="true" 
    android:background="#bc8383"> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Show Second" 
     android:id="@+id/btnShowSecond" 
     android:layout_weight="0.18" /> 

    <EditText 
     android:id="@+id/et1" 
     android:text="et1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="#000000" 
     android:elegantTextHeight="false" 
     android:maxLength="20" 
     android:singleLine="true" 
     android:textAlignment="center" 
     android:textColor="#85b27e" 
     android:textSize="40dp" 
     android:paddingLeft="3dp" 
     android:paddingRight="3dp" 
     android:layout_marginTop="10dp" 
     android:layout_weight="1" /> 
</LinearLayout> 

layout_second.xml

<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" 
    android:orientation="vertical" 
    android:focusable="true" 
    android:background="#bc8383"> 

    <EditText 
     android:id="@+id/et2" 
     android:text="et2" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="#000000" 
     android:elegantTextHeight="false" 
     android:maxLength="20" 
     android:singleLine="true" 
     android:textAlignment="center" 
     android:textColor="#85b27e" 
     android:textSize="40dp" 
     android:paddingLeft="3dp" 
     android:paddingRight="3dp" 
     android:layout_marginTop="10dp" 
     android:layout_gravity="center_horizontal" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="btn2" 
     android:id="@+id/btn2" 
     android:layout_gravity="center_horizontal" /> 
</LinearLayout> 

custom_tab.xml

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/tab" 
    android:textColor="@color/colorAccent" 
    android:textSize="14dp" 
    android:gravity="center" 
    android:fontFamily="@string/font_fontFamily_medium"/> 

MainActivity.java

package xmaxsoft.delfragment; 

import android.os.Bundle; 
import android.support.design.widget.TabLayout; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.LayoutInflater; 
import android.widget.TextView; 
import java.util.ArrayList; 
import java.util.List; 

public class MainActivity extends AppCompatActivity { 
    private Toolbar toolbar; 
    private TabLayout tabLayout; 
    private ViewPager viewPager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     viewPager = (ViewPager) findViewById(R.id.viewpager); 
     setupViewPager(viewPager); 
     tabLayout = (TabLayout) findViewById(R.id.tabs); 
     tabLayout.setupWithViewPager(viewPager); 
     setupTabIcons(); 
    } 

    private void setupTabIcons() { 
     TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
     tabOne.setText("One"); 
     tabLayout.getTabAt(0).setCustomView(tabOne); 

     TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
     tabTwo.setText("Two"); 
     tabLayout.getTabAt(1).setCustomView(tabTwo); 
    } 

    private void setupViewPager(ViewPager viewPager) { 
     ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); 
     adapter.addFrag(new First(), "One"); 
     adapter.addFrag(new Second(), "Two"); 
     viewPager.setAdapter(adapter); 
    } 

    class ViewPagerAdapter extends FragmentPagerAdapter { 
     private final List<Fragment> mFragmentList = new ArrayList<>(); 
     private final List<String> mFragmentTitleList = new ArrayList<>(); 

     public ViewPagerAdapter(FragmentManager manager) { 
      super(manager); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      return mFragmentList.get(position); 
     } 

     @Override 
     public int getCount() { 
      return mFragmentList.size(); 
     } 

     public void addFrag(Fragment fragment, String title) { 
      mFragmentList.add(fragment); 
      mFragmentTitleList.add(title); 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      return mFragmentTitleList.get(position); 
     } 
    } 
} 

First.java

package xmaxsoft.delfragment; 
import android.os.Bundle; 
import android.support.design.widget.TabLayout; 
import android.support.v4.app.Fragment; 
import android.support.v4.view.ViewPager; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.EditText; 

public class First extends Fragment { 
    public First() { 
    } 

    Button btnShowSecond; 
    EditText et1; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     final View view = inflater.inflate(R.layout.layout_first, container, false); 
     btnShowSecond = (Button) view.findViewById(R.id.btnShowSecond); 
     et1 = (EditText) view.findViewById(R.id.et1); 
     btnShowSecond.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
      //what kind of code must be here ??? 
      //what kind of code must be here ??? 
      //what kind of code must be here ??? 
      } 
     }); 
     return view; 
    } 
} 

Second.java

package xmaxsoft.delfragment; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.EditText; 

public class Second extends Fragment { 
    public Second() { 
    } 

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

Antwort

0

Rabatt-Code: -

Fragment fragment = new XXXFragment(); 
     if (fragment != null) { 

FragmentManager fragmentManager =getActivity().getSupportFragmentManager(); 
           fragmentManager.beginTransaction().replace(R.id.frame_container, fragment, "TAG").commit(); 

}

+0

Ihnen für Ihre Antwort danken, aber ich kann das nicht tun. Wo kann ich diesen Code verwenden und was kann ich R.id.frame_container durch ersetzen? – lotomax

+0

Sie können Ihren Code dort einfügen, wo Sie ein neues Fragment anzeigen möchten und dieser R.id.frame_container ist ein Rahmenlayout.

+0

Entschuldigung, ich bin Neuling auf Android und so bitte sagen Sie mir, wie kann ich diesen Code an mein Projekt anpassen? – lotomax

0

Da diese beiden Fragmente derselben Aktivität verwenden,

zum Wert aus ersten Fragments eingestellt:

  public void onClick(View v) { 
      //what kind of code must be here ??? 
      //what kind of code must be here ??? 
      //what kind of code must be here ??? 
    getActivity().getIntent().putExtra("key", "value"); 
      } 

Um Wert aus dem zweiten Fragment zu erhalten:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     final View view = inflater.inflate(R.layout.activity_second, container, false); 
     // 
EditText et2 = (EditText) view.findViewById(R.id.et2); 
String valueofet1 = getActivity().getIntent().getExtras().getString("key"); 
et2.setText(valueofet1); 
     return view; 
    } 
+0

danke, aber wie kann ich Wert erhalten und auf edittext einstellen, kann ich über diesen Code nicht verstehen. – lotomax

+0

check now @lotomax –

+0

Ich habe einen Fehler bei String gefunden valueofet1 = getActivity(). GetIntent(). GetExtras(). GetString ("key"); // diese Zeile "E/AndroidRuntime: FATALE AUSNAHME: Haupt java.lang.NullPointerException bei xmaxsoft.delfragment.Second.onCreateView (Second.java:28)" – lotomax

0

Ersetzen Ein Fragment ist besser aus der Aktivität gemacht.

In Ihrem ersten Fragment auf btnShowSecond klicken Hörer in onClick überprüfen, ob Aktivität nicht null und wenn es eine Instanz der Hauptaktivität und Call-Methode innerhalb von mainActivity, die Fragmente als solche wechseln wird.

if(getActivity()!=null && getActivity instanceof MainActivity){ 
     ((MainActivity)getActivity()).showSecondFragment(); 
} 

Und Ihre ShowSecondFragment() - Methode innerhalb Ihrer MainActivity ist wie folgt.

public void showSecondFragment(){ 
    getSupportFragmentManager().beginTransaction().replace(R.id.<the layout where you want to show second fragment>,new Second()).commit(); 

Bitte lassen Sie mich wissen, wenn Sie irgendwelche Zweifel haben. Hoffe das hilft.

Ein besserer Weg, dies zu tun wäre, die Schnittstelle zu verwenden, um Methoden in Aktivität von Ihrem Fragment aufzurufen.

Sehen Sie sich den folgenden Link an, um mehr über die Fragmentierung der Kommunikation und umgekehrt zu erfahren.

https://laaptu.wordpress.com/tag/android-communication-between-fragment-and-activity/

+0

Ragesh danke für Ihre Antwort, aber ich kann nicht, dass . getSupportFragmentManager() ist unbekannt. Wie kann ich diese Methode gemäß meinem Projekt verwenden? – lotomax

+0

verwenden Sie stattdessen getFragmentManager(). es sollte gut funktionieren –

+0

getFragmentManager() ist in Ordnung, aber jetzt funktioniert der Code nicht. – lotomax

0

Try this:

FragmentManager mFragmentManager; 
FragmentTransaction mFragmentTransaction; 
btnShowSecond.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       mFragmentManager = getFragmentManager(); 
       mFragmentTransaction = mFragmentManager.beginTransaction(); 
       FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.containerView, new second()).addToBackStack("second").commit(); 
      } 
     }); 

auf XML In FrameLayout & i ID- erwähnt containerView hoffen kann es hilft

+0

Ashwini danke für ihre antwort, aber ich habe versucht ihren code aber ich kann nicht das. mFragmentTransaction ise unknow in meinem code. – lotomax

+0

@lotomax gut ich bearbeitet code .. Sie müssen FragmentTransaction deklarieren. Wenn dies hilft, bitte Upvote –

+0

Was kann ich mit "R.id.containerView" ersetzen? – lotomax

Verwandte Themen