无法将函数“OnClickListener”添加到ImageButton

时间:2016-05-28 19:59:46

标签: java android android-imagebutton

这是我的Java代码:

public class MainPage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

TabLayout tabLayout;
ViewPageAdapter viewPageAdapter;
ViewPager viewPager;
ImageButton pfp;
Bitmap bitmap_one;

private String UPLOAD_URL = "http://.php";
private int PICK_IMAGE_REQUEST = 1;
private String KEY_IMAGE = "image";

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


    //id's
    pfp = (ImageButton) findViewById(R.id.imageButton_one);
    pfp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == pfp){
                showFileChooser();
            }
        }
    });


    //SearchIntent
    Intent searchI = getIntent();
    if (Intent.ACTION_SEARCH.equals(searchI.getAction())) {

        String query = searchI.getStringExtra(SearchManager.QUERY);
        Toast.makeText(MainPage.this, query, Toast.LENGTH_SHORT).show();
    }

    //Toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);

    //Tabs
    tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
    viewPager = (ViewPager) findViewById(R.id.viewPager_two);
    viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
    viewPageAdapter.addFragments(new FeedFragment(), "Feed");
    viewPageAdapter.addFragments(new MessagesFragment(), "Messages");
    viewPageAdapter.addFragments(new NotificationsFragment(), "Notifications");
    viewPager.setAdapter(viewPageAdapter);
    tabLayout.setupWithViewPager(viewPager);


    //FloatingActionButton
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });


    //NavigationDrawer
    DrawerLayout 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.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.profile) {

        Intent i = new Intent(this, Profile.class);
        startActivity(i);

    } else if (id == R.id.whatshot) {

        Intent i = new Intent(this, WhatsHot.class);
        startActivity(i);

    } else if (id == R.id.trending) {

        Intent i = new Intent(this, Trending.class);
        startActivity(i);

    } else if (id == R.id.radioplayer) {

        Intent i = new Intent(this, Radio.class);
        startActivity(i);

    } else if (id == R.id.musicplayer) {

        Intent i = new Intent(this, MusicPlayer.class);
        startActivity(i);

    } else if (id == R.id.settings) {

        Intent i = new Intent(this, Settings.class);
        startActivity(i);

    } else if (id == R.id.info) {

        Intent i = new Intent(this, Info.class);
        startActivity(i);

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main_menu, menu);

    SearchView searchView = (SearchView) menu.findItem(R.id.search_view).getActionView();
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return super.onCreateOptionsMenu(menu);
}


//ImageInfo
private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {

            bitmap_one = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            pfp.setImageBitmap(bitmap_one);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



//Typeface
private void initTypeface() {

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
    TextView text = (TextView) findViewById(R.id.toolbarTitle);
    text.setTypeface(myTypeface);

}
}

这是我的XML代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageButton
    android:id="@+id/imageButton_one"
    android:layout_width="90dp"
    android:background="#2A363B"
    android:onClick="pfpClick"
    android:layout_height="90dp"
    android:paddingTop="@dimen/nav_header_vertical_spacing" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text=""
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

</LinearLayout>

我想要完成的是onClick的ImageButton,我可以选择一个文件并添加它。但我不断收到错误:

  

尝试调用虚方法'void   android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)”   在空对象引用上

P.S我的图像按钮位于导航抽屉中。

2 个答案:

答案 0 :(得分:2)

你应该这样做:

android:onClick="pfpClick"

但是你需要在类中定义一个名为pfpClick的方法,并且不存在

或者

pfp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == pfp){
                showFileChooser();
            }
        }
    });

同时是一种不好的做法,对于第二种选择 这不是必要的:

if (v == pfp){ 

因为您正在实施的侦听器是匿名的

我建议在布局中删除它:

 android:onClick="pfpClick"

然后清理/修改监听器片段:

pfp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showFileChooser();

        }
    });

答案 1 :(得分:0)

看起来行pfp = (ImageButton) findViewById(R.id.imageButton_one);返回一个空对象。

如果你的XML出现问题(你没有使用正确的布局,或者视图id与XML中的那个不匹配),这是合乎逻辑的

另一种情况可能是您必须执行Build -> Clean Project,然后重建并运行您的应用。