0

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

MainActivity

public class MainActivity extends AppCompatActivity {

  MainFragment mainFragment;
  FragmentHome fragmentHome;
  int state;
  SearchView homeSearchView;
  Button buttonSendToFragment;


  private Fragment fragment;
  private FragmentManager fragmentManager;
  final String LOG_TAG = "myLogs";


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
    //        bottomNavigationView.inflateMenu(R.menu.bottom_nav_items);

    Log.d(LOG_TAG, "nachalo");

    fragmentManager = getSupportFragmentManager();


    fragment = new FragmentHome();
    final FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.myfragment, fragment).commit();


    bottomNavigationView.setOnNavigationItemSelectedListener(
      new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
          switch (item.getItemId()) {
            case R.id.menu_home:
              fragment = new FragmentHome();
              state = 1;
              Log.d(LOG_TAG, "state 1");
              break;
            case R.id.menu_favorites:
              fragment = new MainFragment();
              state = 2;
              break;
            case R.id.menu_add:
              state = 3;
              break;
            case R.id.menu_message:
              state = 4;
              break;
            case R.id.menu_profile:
              state = 5;
              break;
          }

          final FragmentTransaction transaction = fragmentManager.beginTransaction();
          transaction.replace(R.id.myfragment, fragment).commit();
          return false;
        }
      });


    buttonSendToFragment = (Button) findViewById(R.id.buttonSendToFragment);

    buttonSendToFragment.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View view) {
        // TODO Auto-generated method stub
        TextView textFragment = (TextView) findViewById(R.id.fragmenttext);
        textFragment.setText("Кнопка нажата");
      }
    });
  }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/buttonSendToFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/myfragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="@color/colorPrimary"
            android:orientation="vertical">

        </FrameLayout>

        <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_items" />

    </LinearLayout>


</LinearLayout>

FragmentHome

public class FragmentHome extends Fragment implements View.OnClickListener {
    Button buttonFilter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub


        View rootView =
                inflater.inflate(R.layout.layout_home, container, false);


        Button buttonFilter = (Button) getActivity().findViewById(R.id.buttonFilter);
        buttonFilter.setOnClickListener(this);

        return rootView;
    }


    @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), "Проверка",
                Toast.LENGTH_SHORT).show();
    }
}

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fl_home">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginRight="8dp"
            android:layout_marginLeft="8dp">

            <LinearLayout
                android:id="@+id/homeLinearLayout"
                android:layout_width="match_parent"
                android:layout_height="56dp"
                android:layout_alignParentTop="false"
                android:layout_marginBottom="4dp"
                android:background="@android:color/holo_green_light"
                android:gravity="center"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/buttonFilter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="8dp"
                    android:background="@android:color/transparent"
                    app:srcCompat="@android:drawable/ic_menu_sort_by_size" />

                <SearchView
                    android:id="@+id/homeSearchView"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_margin="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorSearchView"
                    android:gravity="center"
                    android:iconifiedByDefault="true"
                    android:queryHint="Search" />

                <ImageButton
                    android:id="@+id/imageButton2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="8dp"
                    android:background="@android:color/transparent"
                    app:srcCompat="@android:drawable/ic_menu_my_calendar" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:background="@android:color/holo_orange_light"
                android:orientation="vertical">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/homeRecyclerView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@+id/homeLinearLayout">

                </android.support.v7.widget.RecyclerView>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

1 ответ 1

0

Михаил, если я Вас правильно понял, то это должно помочь

package com.example.android.test;


import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class FragmentHome extends Fragment implements View.OnClickListener{
    Button buttonFilter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub


        View rootView =
                inflater.inflate(R.layout.layout_home, container, false);


 //       Button buttonFilter = (Button) getActivity().findViewById(R.id.buttonFilter);
 //       buttonFilter.setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onStart()  {
        super.onStart();
        Button buttonFilter = (Button) getView().findViewById(R.id.buttonFilter);
        buttonFilter.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), "Проверка",
                Toast.LENGTH_SHORT).show();
    }
}

но до сих пор приложение вылетает. В логах пишет:

Process: com.example.android.test, PID: 15010
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.test/com.example.android.test.MainActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button

введите сюда код
2
  • Значит твоя buttonFilter в xml задана не как Button а как AppCompatImageButton, приведи код и xml к одному типу. И вызывай view.findViewById() в методе onViewCreated() своего фрагмента!
    – yno7
    20 окт 2018 в 22:34
  • Большое спасибо. Все заработало 20 окт 2018 в 23:46

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.