简体   繁体   English

从mainactivity开始新片段

[英]Starting new fragment from mainactivity

I read a lot of questions here, but I didn't get a proper solution for my problem. 我在这里阅读了很多问题,但是没有为我的问题找到合适的解决方案。 I have a MainActivity java class, and I have several activities in for my app. 我有一个MainActivity java类,并且我的应用程序中有几个活动。 Now, I created a "Tabbed activity" automatically in Android Studio. 现在,我在Android Studio中自动创建了一个“带标签的活动”。 I do have a Imagebutton which I use for opening a new fragment. 我确实有一个Imagebutton,用于打开新片段。 This new fragment is called "Generaldiscription". 这个新片段称为“通用名称”。 I learned, that a fragment can't be started like an activity, I need to use FragmentManagener to get a fragment open. 我了解到,片段不能像活动一样开始,我需要使用FragmentManagener来打开片段。 My app starts, but when I click on the imagebutton, where actually my fragment should start, the app crashes. 我的应用程序启动了,但是当我单击图像按钮(实际上应该从哪里开始)时,应用程序崩溃了。

In the following, you can see my mainactivity.java, and the fragments as java and as xml. 在下面,您可以看到我的mainactivity.java,以及Java和XML片段。 Thank you in anticipation. 谢谢您的期待。

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    final ImageButton generaldiscriptionbutton = (ImageButton) findViewById(R.id.imageButton);
    setSupportActionBar(toolbar);
    checkFirstRun();



    generaldiscriptionbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            Generaldiscription fragment = new Generaldiscription();
            fm.beginTransaction().add(R.id.main_content, ); // don't know what to write here.



        }
    });

My activity_generaldiscription.xml which was created automatically 我的activity_generaldiscription.xml是自动创建的

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
 >


<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <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/AppTheme.PopupOverlay">

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


</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

My fragment_generaldiscription.xml: 我的fragment_generaldiscription.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="com.example.user.myapp.Generaldiscription$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:text="fffff" />

EDIT my generaldiscription.java 编辑我的generaldiscription.java

 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;

 import android.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
  import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;

import android.widget.TextView;

public class Generaldiscription extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_generaldiscription, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_generaldiscription, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

} }

Start your fragment this way: 这样开始片段:

            FragmentManager fragmentmanager = getFragmentManager();
            fragmentmanager.beginTransaction()
                .replace(R.id.main_content
                        , new Generaldiscription())
                .commit();

EDIT 编辑

In your case you should start you Generaldiscription like this: 在您的情况下,您应该像这样开始Generaldiscription:

            Intent myIntent = new Intent(MainActivity.this, Generaldiscription.class);
            MainActivity.this.startActivity(myIntent);

What is more, your GeneralDiscription should import android.support.v4.app.Fragment; 而且,您的GeneralDiscription应该导入android.support.v4.app.Fragment; instead of android.app.Fragment; 而不是android.app.Fragment;

From the Documentation 文档中

FragmentTransaction add (int containerViewId, 
                Fragment fragment, 
                String tag)

Add a fragment to the activity state. 将片段添加到活动状态。 This fragment may optionally also have its view (if Fragment. onCreateView returns non-null) inserted into a container view of the activity. 该片段任选地也可具有其视图(如果片段。 onCreateView返回非空)插入活动的容器图。

Parameters 参量

  • containerViewId int : Optional identifier of the container this fragment is to be placed in. If 0, it will not be placed in a containerViewId int :要放置此片段的容器的可选标识符。如果为0,则不会将其放置在
    container. 容器。
  • fragment Fragment : The fragment to be added. fragment Fragment :要添加的片段。 This fragment must not already be added to the activity. 该片段必须尚未添加到活动中。
  • tag String : Optional tag name for the fragment, to later retrieve the fragment with tag String :片段的可选标记名称,以便以后使用

    FragmentManager.findFragmentByTag(String).

so in your code write: 所以在你的代码中写:

FragmentManager manager = getSupportFragmentManager();
Generaldiscription fragment = new Generaldiscription();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.main_content,fragment,"Tag");
transaction.addToBackStack(null);
transaction.commit();

And in your Generaldiscription Fragment: 在您的Generaldiscription片段中:

import android.support.v4.app.Fragment;  //make sure you import the support package

public class Generaldiscription extends Fragment {

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

Declare in your fragment like this 像这样声明你的片段

public interface OnClickListener {
    void onClick();
}
private final OnClickListener listener;

In your button click listener add this 在您的按钮中,单击“侦听器”

if(listener!=null){
      listener.onclick();
}

In your Activity, implements this listener and add this to the fragment than you can hide current fragment and show second fragment in onClick method in Activity 在您的Activity中,实现此侦听器并将其添加到片段中,这样您就可以隐藏当前片段并在Activity中的onClick方法中显示第二个片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM