Android Eclipse Start Fragment from TabLayout Tab

亡梦爱人 提交于 2019-12-25 02:58:49

问题


I have implemented a TabLayout which has a few tabs & one of the tabs has a table & when a user clicks on a row in the table I need it to get rid of the tab layout, except for the toolbar & open up a new Fragment.

I've tried a few different ways but nothing seems to work, if anyone has any ideas, it'll will be much appreciated!

Thank you! Cheers!

This is the activity_main.xml

<RelativeLayout
android:id="@+id/main_layout"
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=".MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/toolbar"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

</RelativeLayout>

& this is the MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

& this is tab1.xml

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" 
android:background="#F0F0F0" >

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:gravity="center" >
<TableLayout
    android:id="@+id/table"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center" >
</TableLayout>

<RelativeLayout
    android:id="@+id/loadingPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true" />
</RelativeLayout>

</FrameLayout>

& this is Tab1.java

public class TopStories extends Fragment {

A lot of code goes here............

    public void createTable() {

    TableLayout table = (TableLayout)          getActivity().findViewById(R.id.table);
    table.setBackgroundColor(Color.rgb(240, 240, 240));
    table.setStretchAllColumns(true);
    table.setShrinkAllColumns(true);

    table.removeAllViews();

TableRow row = new TableRow(getActivity());
        row .setGravity(Gravity.CENTER);
        row .setPadding(0, 10, 0, 10);
        row .setBackgroundColor(Color.WHITE);
        row .setClickable(true);
        TableRow.LayoutParams params = new TableRow.LayoutParams();

        row .setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                This is where I need to start up the new fragment (NewFragment.Java).

            }


        });

    }

}

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

}

NewFragment.java

public class NewFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.newfragment, container, false);        
}

}

newfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1.04" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="18dp"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="87dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

</LinearLayout>

回答1:


I think you need to give the fragment somewhere to replace. Here is the XML from my app, and when I swap fragments, they post to flcontent.

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk
xmlns:app="http://schemas.android.com/apk/res
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!-- The ActionBar -->
    <include
        layout="@layout/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
</LinearLayout>
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
    android:id="@+id/nvView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/white"
    app:menu="@menu/drawer_view"
    app:headerLayout="@layout/nav_header"/>

and the class code

 // Insert the fragment by replacing any existing fragment
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.flContent, fragment);
    ft.addToBackStack(null);
    ft.commit();



回答2:


Alright so I think that I figured out a really cheap & a cheeky way to do this & probably not very healthy for the app but it works perfect!

Thank you very much for the help Brian! Appreciate it! Maybe you can do this for the backstack problem of your app as well, don't know if it will work or the right thing that you need to do though.

Cheers!

Added a FrameLayout to my main_activity.xml

<RelativeLayout
android:id="@+id/main_layout"
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=".MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/toolbar"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

<FrameLayout
    android:id="@+id/flContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

</RelativeLayout>

Changed my newfragment.xml to this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fullStoryLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RelativeLayout
    android:id="@+id/fullStoryRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1.04" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="80dp"/>

    <TextView
        android:id="@+id/fullStorytitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/fullStory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/image"
        android:layout_marginTop="50dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

</LinearLayout>

& added this to the onClick event of the table row

row.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                      getActivity().findViewById(R.id.tab_layout).setVisibility(View.GONE);
                   getActivity().findViewById(R.id.pager).setVisibility(View.GONE);


                   ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                  ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("New Fragment");

                Fragment fragment = null;

                Class fragmentClass = NewFragment.class;
                try {
                    fragment = (Fragment) fragmentClass.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                FragmentManager fragmentManager =   getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction =   fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.flContent, fragment);
                fragmentTransaction.commit();

            }


        });

& to go back to the main TabLayout from the NewFragment, I added this at MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
    case android.R.id.home:
        onBackPressed();
       return true;
   default:
    return super.onOptionsItemSelected(item);
    }
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch(keyCode){
    case KeyEvent.KEYCODE_BACK:
        if (getSupportActionBar().getTitle() != "Main Activity"){
            onBackPressed();
        }
        else {
            System.exit(0);
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public void onBackPressed(){
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    getSupportActionBar().setTitle("Main Activity");
    findViewById(R.id.fullStoryLinearLayout).setVisibility(View.GONE);
    findViewById(R.id.tab_layout).setVisibility(View.VISIBLE);
    findViewById(R.id.pager).setVisibility(View.VISIBLE);

}



来源:https://stackoverflow.com/questions/32800246/android-eclipse-start-fragment-from-tablayout-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!