【问题标题】:Android Eclipse Start Fragment from TabLayout TabAndroid Eclipse 从 TabLayout 选项卡启动片段
【发布时间】:2015-09-26 17:58:59
【问题描述】:

我已经实现了一个 TabLayout,它有几个选项卡,其中一个选项卡有一个表格,当用户单击表格中的一行时,我需要它来摆脱选项卡布局,除了工具栏和打开一个新的片段。

我尝试了几种不同的方法,但似乎没有任何效果,如果有人有任何想法,将不胜感激!

谢谢! 干杯!

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

&这是 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);
}

}

&这是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>

&这是 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>

【问题讨论】:

    标签: java android eclipse android-fragments android-tablayout


    【解决方案1】:

    我认为您需要将片段放在某个地方进行替换。这是我的应用程序中的 XML,当我交换片段时,它们会发布到 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"/>
    

    类代码

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

    【讨论】:

    • R.id.flcontent 是我的 mainactivity.xml 中的框架布局。该 xml 有我的导航、工具栏等,我只是交换片段
    【解决方案2】:

    好吧,所以我认为我找到了一种非常便宜且厚颜无耻的方法来执行此操作,并且可能对应用程序不太健康,但它非常有效!

    非常感谢布赖恩的帮助!欣赏它!也许您也可以为您的应用程序的 backstack 问题执行此操作,但不知道它是否会起作用或您需要做的正确的事情。

    干杯!

    在我的 main_activity.xml 中添加了 FrameLayout

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

    把我的 newfragment.xml 改成这个

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

    & 将此添加到表格行的 onClick 事件中

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

    & 要从 NewFragment 返回主 TabLayout,我在 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);
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多