【发布时间】:2018-02-07 00:21:34
【问题描述】:
我在setContentView、findViewById 和getSupportFragmentManager() 遇到错误。该代码在扩展 AppCompatActivity 时运行良好,但是当我尝试将其更改为片段时,它会出现错误。我需要将 Activity 的这段代码转换为片段,以便我可以在navigationDrawer 中使用它。
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.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
public class PerdidosActivity extends Fragment {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perdidos);
// get the reference of FrameLayout and TabLayout
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("First"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.android_icon); // set an icon for the
// first tab
tabLayout.addTab(firstTab); // add the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Second"); // set the Text for the second Tab
secondTab.setIcon(R.drawable.android_icon); // set an icon for the second tab
tabLayout.addTab(secondTab); // add the tab in the TabLayout
// perform setOnTabSelectedListener event on TabLayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
【问题讨论】:
标签: android android-studio android-fragments fragment navigation-drawer