Присвоение идентификатора просмотру пейджера Такие элементы, как кнопки, не будут работать - PullRequest
2 голосов
/ 16 мая 2019

Я хочу реализовать View Pager, содержащий две страницы с данными, и обе содержат строку поиска, кнопку и представление списка. Обе панели просмотра должны получать данные из SQLite ... Когда я пытаюсь присвоить идентификаторы кнопкам и списку в файле Java, приложение получает сбой и говорит, что это невозможно здесь.

Вот мой главный фрагмент

{
ListView listViewclients;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_fragment);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setTitle("Dynamic ERPMini");
    TabLayout tabLayout = findViewById(R.id.tab_layout);

    //listViewclients=findViewById(R.id.listclient);

    tabLayout.addTab(tabLayout.newTab().setText("Clients"));
    tabLayout.addTab(tabLayout.newTab().setText("Products"));
    tabLayout.addTab(tabLayout.newTab().setText("Invoices"));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = findViewById(R.id.pager);
    final PagerAdapter adapter = new PagersAdapter(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) {

        }
    });
}
}

Вот клиенты.java

{
ListView listView;
Button btnAll;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.clients, container, false);
}

}

Вот второй слайд

{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.products, container, false);
}
}

Вот XML-файлы продукта и клиента

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:orientation="vertical">

<SearchView
    android:id="@+id/searchclient"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutDirection="rtl"
    android:layout_alignParentRight="true">

</SearchView>

<Button
    android:id="@+id/searchall"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/searchclient"
    android:layout_marginTop="15dp"
    android:background="@color/colorPrimaryDark"
    android:padding="10dp"
    android:text="Search All"
    android:textColor="@color/colorPrimary" />

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

Вот XML-файл продукта

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:orientation="vertical">

<SearchView
    android:id="@+id/searchproduct"
    android:layout_width="match_parent"
    android:outlineSpotShadowColor="@color/colorPrimary"
    android:layout_height="wrap_content"
    android:layoutDirection="rtl"
    android:layout_alignParentRight="true">
</SearchView>

<Button
    android:id="@+id/searchallproducts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/searchproduct"
    android:layout_marginTop="15dp"
    android:background="@color/colorPrimary"
    android:padding="10dp"
    android:text="Search All"
    android:textColor="@color/colorPrimary" />

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

Здесь ошибка больше Изображение местоположения ошибки

Вот Logcat

ava.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tablewithlist/com.example.tablewithlist.MainFragment}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    at android.app.ActivityThread.access$600(ActivityThread.java:130)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.example.tablewithlist.MainFragment.onCreate(MainFragment.java:29)
    at android.app.Activity.performCreate(Activity.java:5008)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
    at android.app.ActivityThread.access$600(ActivityThread.java:130) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loop(Looper.java:137) 
    at android.app.ActivityThread.main(ActivityThread.java:4745) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:511) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
    at dalvik.system.NativeStart.main(Native Method) 

Вот изображение после передачи идентификаторов классу client.java Image Of Passing ID to Client.java

Вот мой основной файл фрагмента.xml

<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/colorPrimary"
tools:context="com.example.tablewithlist.MainFragment">
    <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="@color/colorHeaderBackground"
        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="@color/colorHeaderBackground"
        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"/>

1 Ответ

4 голосов
/ 16 мая 2019

Вы должны получить раздутый вид, чтобы инициализировать кнопку и другие виды.

{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view= inflater.inflate(R.layout.products, container, false);
    buttonAll= view.findViewById(R.id.button);

    buttonAll.setOnClickListener(new OnClickListener()
    {
             @Override
             public void onClick(View v)
             {
                // do something
             } 
    }); 

    return view;
}

Инициализировал все представления, подобные этому, во фрагменте. Это решит проблему. Вы также можете использовать библиотеку ButterKnife, чтобы связать вид.

вот ссылка: ButterKnife

MainFragment

public class MainFragment extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_fragment);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("Dynamic ERPMini");

        TabLayout tabLayout = findViewById(R.id.tab_layout);


        tabLayout.addTab(tabLayout.newTab().setText("Clients"));
        tabLayout.addTab(tabLayout.newTab().setText("Products"));
        tabLayout.addTab(tabLayout.newTab().setText("Invoices"));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = findViewById(R.id.pager);
        final PagerAdapter adapter = new PagersAdapter(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) {

            }
        });
    }
}

Clients.Java

public class Clients extends Fragment {
    ListView listView;
    Button btnAll;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.clients, container, false);
        btnAll=view.findViewById(R.id.searchall);
        listView=view.findViewById(R.id.Viewclients);

        btnAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Usman", Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

}
...