2015-09-26 2 views
0

Я внедрил TabLayout, у которого есть несколько вкладок &, на одной из таблиц есть таблица &, когда пользователь нажимает на строку в таблице, мне нужно ее, чтобы избавиться от макета вкладки, кроме панели инструментов & открыть новый фрагмент.Android Eclipse Начало фрагмента из вкладки 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> 

ответ

0

Я думаю, что вам нужно, чтобы дать фрагмент где-то заменить. Вот XML из моего приложения, и когда я обмениваюсь фрагментами, они публикуют сообщение.

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

R.id.flcontent - это рамка в моей основной activity.xml. У этого xml есть мой nav, панель инструментов и т. Д., И я просто заменяю фрагменты –

0

Хорошо, так что я думаю, что я понял, действительно дешевый & дерзкий способ сделать это &, вероятно, не очень здорово для приложения, но это работает отлично!

Большое спасибо за помощь Брайана! Ценить это! Возможно, вы можете сделать это для проблемы с backstack вашего приложения, а также не знаете, будет ли это работать или что нужно делать.

Cheers!

Добавлен FrameLayout к моему 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> 

изменил мою 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(); 

      } 


     }); 

&, чтобы вернуться к главному TabLayout из NewFragment, я добавил это в 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); 

Смежные вопросы