按钮监听器不工作

时间:2018-03-18 06:46:50

标签: java android

其布局包含button1

的片段
package com.example.shrey.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 */
public class PageFragment extends android.support.v4.app.Fragment {

    public PageFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.page_fragment_layout,container,false);

//      button initialisation
        Button button_a;
        button_a = view.findViewById(R.id.button1);
        button_a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(PageFragment.this,
                        ScrollingActivity1.class);
                startActivity(myIntent);
            }
        });

        return view;
    }

}

在调试时我收到错误:

  

" java.lang.NullPointerException:尝试调用虚方法' void android.view.View.setOnClickListener(android.view.View $ OnClickListener)'在null对象引用"

我正在提供我的MainActivity代码。 编辑 - 添加我的程序的zip文件。 note- button1是activity_main.xml的viewpager中某个页面上的按钮。 我做了一个我想在点击button1

时显示的活动

activity_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:id="@+id/Constraint1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    tools:context="com.example.shrey.myapplication.MainActivity">

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <!--code for action bar-->
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimaryDark"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

        <!--swipe view creating code-->
        <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="16dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>
        <!--code for navigation drawer-->
        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_view" />
    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

MainActivity

package com.example.shrey.myapplication;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import static javax.xml.datatype.DatatypeFactory.newInstance;

public class MainActivity  extends AppCompatActivity {
    private DrawerLayout drawerlayout;
    ViewPager viewpager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerlayout = findViewById(R.id.drawer_layout);

        viewpager = findViewById(R.id.view_pager);
        SwipeAdapter swipeadapter = new SwipeAdapter(getSupportFragmentManager());
        viewpager.setAdapter(swipeadapter);

//        set status bar color code
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(this.getResources().getColor(R.color.material_blue_grey_950));
        }

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionbar = getSupportActionBar();
        actionbar.setDisplayHomeAsUpEnabled(true);
        actionbar.setHomeAsUpIndicator(R.drawable.ic_navdrawer);
//        <!-- code to change title and its color. -->
        actionbar.setTitle(Html.fromHtml("<font color='#ffffff'>Skill India App </font>"));

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                        // set item as selected to persist highlight
                        menuItem.setChecked(true);
                        // close drawer when item is tapped
                        drawerlayout.closeDrawers();

                        // Add code here to update the UI based on the item selected
                        // For example, swap UI fragments here

                        return true;
                    }
                });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                drawerlayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:1)

我只看到一个setOnClickListener,所以代码的问题在这里:

//      button initialisation
        Button button_a;
        button_a = findViewById(R.id.button1);
        button_a.setOnClickListener(new View.OnClickListener() {

您正在创建一个名为button_a的Button(最初为null),然后将其与findViewById绑定。问题是findViewById没有在内容视图中找到id为“button1”的任何内容,在本例中为R.layout.activity_main。因此,当运行下一行时,button_a仍为null,并且您正在执行null.setOnClickListener,这是不允许的。

如Bhuvanesh BS所述,需要更多信息来完整回答,发布了您的activity_main.xml。

答案 1 :(得分:1)

首先,您无法在intent中拨打Button button_a; button_a = view.findViewById(R.id.button1); button_a.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(MainActivity.this, ScrollingActivity1.class); startActivity(myIntent); } }); 课程。片段是您包含的活动的一部分。把你的活动名称放在那里。

SwipeAdapter

然后,我无法在代码中看到您将片段添加到viewpager的位置。您需要将片段的实例添加到寻呼机以查看您创建的实际布局,我认为它位于button1

最后,摆脱onCLickListener班级中的MainActivity {{1}}。

它会起作用