Всем доброго времени суток, я использую левую панель навигации, а для активности на панели навигации использую фрагмент. Но проблема в том, что как только я нажимаю на действие, фрагмент не может отображаться. Я не уверен, в чем проблема.
Основная деятельность
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
informationList = new ArrayList<>();
adapter = new AlbumsAdapter(this, informationList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,
2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2,
dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
prepareAlbums();
//Cover Pic
try {
Glide.with(this).load(R.drawable.project1_cover).into((ImageView)
findViewById(R.id.backdrop));
} catch (Exception e) {
e.printStackTrace();
}
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setupDrawerContent(navigationView);
}
public void selectedItemDrawer(MenuItem menuItem){
Fragment myFragment = null;
Class fragment = null;
switch(menuItem.getItemId()){
case R.id.checkIn:
Toast.makeText(getApplicationContext(), "Check-In",
Toast.LENGTH_SHORT).show();
break;
case R.id.checkOut:
Toast.makeText(getApplicationContext(), "Check-Out",
Toast.LENGTH_SHORT).show();
break;
case R.id.applyOff:
break;
case R.id.reportBug:
break;
case R.id.manageProfile:
fragment = fragment_manageProfile.class;
break;
case R.id.logout:
break;
default:
break;
}
try{
myFragment = (Fragment)fragment.newInstance();
}catch(Exception e){
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frameLayout,
myFragment).addToBackStack(null).commit();
menuItem.setChecked(true);
drawer.closeDrawers();
}
content_main xml-файл
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
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"
android:background = "@color/viewBg"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = "info.androidhive.kopilim.MainActivity"
tools:showIn = "@layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id = "@+id/recycler_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:clipToPadding = "false"
android:scrollbars = "vertical" />
</RelativeLayout>
app_bar_main 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:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
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:popupTheme = "@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout = "@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
activity_main 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"
android:id = "@+id/main_content"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:background = "@android:color/white"
android:fitsSystemWindows = "true">
<android.support.design.widget.AppBarLayout
android:id = "@+id/appbar"
android:layout_width = "match_parent"
android:layout_height = "@dimen/detail_backdrop_height"
android:fitsSystemWindows = "true"
android:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id = "@+id/collapsing_toolbar"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:fitsSystemWindows = "true"
app:contentScrim = "?attr/colorPrimary"
app:expandedTitleMarginEnd = "64dp"
app:expandedTitleMarginStart = "48dp"
app:expandedTitleTextAppearance = "@android:color/transparent"
app:layout_scrollFlags = "scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content">
<ImageView
android:id = "@+id/backdrop"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:fitsSystemWindows = "true"
android:scaleType = "centerCrop"
app:layout_collapseMode = "parallax" />
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id = "@+id/toolbar"
android:layout_width = "match_parent"
android:layout_height = "?attr/actionBarSize"
app:layout_collapseMode = "pin"
app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout = "@layout/content_main" />
<FrameLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:id = "@+id/frameLayout"
android:background = "@drawable/login_background">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
PS фрагментLayout сейчас находится в моем файле activity_main.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"
tools:context = "info.androidhive.kopilim.fragment_manageProfile">
<ScrollView
android:layout_width = "match_parent"
android:layout_height = "match_parent">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "10dp"
android:orientation = "vertical">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:layout_marginBottom = "35dp"
android:textSize = "22dp"
android:textColor = "#10019f"
android:textStyle = "bold"
android:text = "@string/manageProfile"/>
<TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/empEmail"
android:text = "@string/email"
android:layout_margin = "10dp"
android:textSize = "18dp"
android:gravity = "center_vertical"
android:textColor = "@color/colorAccent"
/>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textColorHint = "@color/colorAccent"
android:layout_margin = "5dp">
<EditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/empID"
android:hint = "@string/profileID"
android:textColor = "@color/colorAccent"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textColorHint = "@color/colorAccent"
android:layout_margin = "5dp">
<EditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/empName"
android:hint = "@string/profileName"
android:textColor = "@color/colorAccent"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textColorHint = "@color/colorAccent"
android:layout_margin = "5dp">
<EditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/empIC"
android:hint = "@string/profileIC"
android:textColor = "@color/colorAccent"
/>
</android.support.design.widget.TextInputLayout>
<RadioGroup
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/radioGroup"
android:layout_margin = "5dp"
android:orientation = "horizontal"
android:weightSum = "1"
>
<RadioButton
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/male"
android:id = "@+id/maleRadio"
android:textColor = "@color/colorAccent"
android:layout_weight = "0.3"
android:checked = "true" />
<RadioButton
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/female"
android:id = "@+id/femaleRadio"
android:textColor = "@color/colorAccent"
android:layout_weight = "0.3"/>
</RadioGroup>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textColorHint = "@color/colorAccent"
android:layout_margin = "5dp">
<EditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/empPh"
android:hint = "@string/profileHp"
android:textColor = "@color/colorAccent"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textColorHint = "@color/colorAccent"
android:layout_margin = "5dp">
<EditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/empAddress"
android:hint = "@string/profileAddress"
android:textColor = "@color/colorAccent"
/>
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginTop = "40dp"
android:layout_marginLeft = "10dp"
android:layout_marginRight = "10dp"
android:id = "@+id/profileBtn"
android:text = "@string/updateProfileBtn"
android:background = "@color/buttonLogin"/>
</LinearLayout>
</ScrollView>
</FrameLayout>
фрагмент java-класса
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_manage_profile, container,
false);
....
....
//my activity
return v;
}
@salman не показывает ошибки. но просто не показывается фрагмент. Оппс, забыл опубликовать мой класс фрагмента, я опубликую здесь свой класс фрагмента.
FrameLayout подходит для файла макета вашей деятельности, потому что вы хотите отображать фрагмент на том же экране. По поводу отображения фрагмента. У вас должен быть собственный класс фрагмента, чтобы отображать его представление и поддерживать его бизнес-логику.
public void selectedItemDrawer(MenuItem menuItem){
Fragment myFragment = null;
Class fragment = null;
switch(menuItem.getItemId()){
case R.id.checkIn:
Toast.makeText(MainActivity.this, "Check-In",
Toast.LENGTH_SHORT).show();
break;
case R.id.checkOut:
Toast.makeText(MainActivity.this, "Check-Out",
Toast.LENGTH_SHORT).show();
break;
case R.id.applyOff:
break;
case R.id.reportBug:
break;
case R.id.manageProfile:
showMyFragment();
break;
case R.id.logout:
break;
default:
break;
}
}
public void showMyFragment(){
Fragment menuFragment = new MyCustomFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frameLayout, menuFragment).commit();
}
И здесь нужно объявить собственный класс фрагмента:
public class MyCustomFragment extends Fragment {
//this text view is got from the xml below
private TextView tvTest;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindView(view);
//start your logic here
}
private void bindView(View view){
tvTest = view.findViewById(R.id.tv_fragment_test);
Toast.makeText(getContext(),tvTest.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
my_fragment_layout.xml
// could be any kind of layout
// for example
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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:orientation = "vertical">
<TextView
android:id = "@+id/tv_fragment_test"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "I'm showing on a fragment"
android:src = "@drawable/app_img_small" />
</LinearLayout>
извини. Я до сих пор путаю этот кастомфрагмент. Какая функция? Можете объяснить это просто? Спасибо чувак.
@DavidAdam уверен: D. Этот настраиваемый фрагмент создается для замены FrameLayout, добавленного в ваше действие. В основном настраиваемый фрагмент представляет собой представление, которое создается при запуске фрагмента. Вы хотели использовать фрагмент при нажатии на панель навигации, таким образом, фрагмент будет создан, когда вы это сделаете, но в вашем коде нет ссылки на какой-либо существующий фрагмент, и вы просто создаете ссылку на класс фрагмента по умолчанию это не поддерживает никакого взгляда на это. Другими словами, фрагмент имеет свою раскладку, и вы можете рассматривать его как «другой экран».
спасибо, чувак, но как мне связать свою активность фрагмента с настраиваемым фрагментом?
Посмотрите выше в примере public void showMyFragment(){ Fragment menuFragment = new MyCustomFragment(); FragmentManager fragmentManager = getSupportFragmentManager();, здесь я создаю новый экземпляр пользовательского фрагмента, Fragment menuFragment = new MyCustomFragment();, затем я заменяю FrameLayout из активности на menuFragment, который представляет экземпляр пользовательского фрагмента.
Что печатает ваша трассировка стека? Наверное, не может создать новый фрагмент. а что такое фрагмент?