如何用按钮打开上下文菜单?

时间:2016-02-25 22:32:16

标签: java android button menu onclick

我试图改变我在应用程序中打开contextmenu的方式, 现在,要打开上下文菜单,我需要长时间点击该项目(在列表视图中),并完美地完成其工作。 我想更改它并在列表视图的每一行旁边添加一个按钮,然后单击按钮,将打开上下文菜单。

我将一个ImageButton添加到rawlayout.xml(我现在看到每行旁边的按钮)但是我无法从活动中获取该按钮。 当我尝试访问该按钮时,该应用程序崩溃并显示以下消息:java.lang.NullPointerException: Attempt to read from field 'android.widget.ImageButton com.grade.ido.grades.ListDataAdaptar$LayoutHandler.BUTTON' on a null object reference.

当前上下文菜单发生在DataListActivity.java

2016年2月26日更新:我更新了相关代码:

我希望我可以为DataListActivity.java中listview中的每一行获取ImageButton。但是我收到了NullPointerException错误。

正如你所看到的,在DataListActivity的sortList函数中,我声明了imageButton(我也尝试在活动的顶部声明,但是我得到了相同的null错误)。

当我在ListDataAdapter中设置onclicklistner时,我可以访问listview中的每一行imageButton,并为每个行弹出一个不同的吐司,但是我无法创建新的上下文菜单。

是否可以通过listDataAdapter上的onclick调用DataListActivity中的contextmenu?

这是我的DataListActivity.java:

package com.grade.ido.grades;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.text.DecimalFormat;
import java.util.Vector;

public class DataListActivity extends ActionBarActivity {
    ListView listView;
    SQLiteDatabase sqLiteDatabase;
    com.grade.ido.grades.CourseDbHelper courseDbHelper;
    Cursor cursor;
    com.grade.ido.grades.ListDataAdaptar listDataAdaptar;
    Spinner sortSpinner;
    Spinner yearSpinner;
    Spinner semSpinner;
    ArrayAdapter<String> sortAdapter;
    ArrayAdapter<String> filterYearAdapter;
    ArrayAdapter<String> filterSemAdapter;
    private InterstitialAd mInterstitialAd;
    private String tempGradeOld,tempGradeNew;
    private String byYear,bySem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(com.grade.ido.grades.R.layout.update_course);
        hideActionBar();
        sortSpinner = (Spinner)findViewById(com.grade.ido.grades.R.id.sortSpinner);
        yearSpinner = (Spinner)findViewById(R.id.yearSpinner);
        semSpinner = (Spinner)findViewById(R.id.semSpinner);
        String[] sortItems = new String[]{"Sort by","Course name","Year","Semester", "Grade", "Points"};
        Vector<String> semItems = new Vector<>();
        semItems.add("all");
        sortAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, sortItems);
        filterYearAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, new  getData(getApplicationContext()).getYearItems());
        filterSemAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, semItems);
        sortSpinner.setAdapter(sortAdapter);
        semSpinner.setAdapter(filterSemAdapter);
        yearSpinner.setAdapter(filterYearAdapter);
        Bundle extras = getIntent().getExtras();
        bySem="all";
        byYear="all";
        courseDbHelper = new com.grade.ido.grades.CourseDbHelper(getApplicationContext());
        sqLiteDatabase = courseDbHelper.getReadableDatabase();
     //   System.out.println(extras.getString("SPINNER"));
        int spinnerPosition = sortAdapter.getPosition(extras.getString("SORT_SPINNER"));

       sortSpinner.setSelection(spinnerPosition);
        System.out.println("extrras data " + extras);
        if (extras==null){
            Log.e("DATALISTACTIVITY", "extras null");

        }
        else {
            Log.e("DATALISTACTIVITY", extras.toString());
        }
        TextView tAVR = (TextView) findViewById(R.id.avrAllCourse);
        double tempAvr = new getData(getApplicationContext()).getTaverage();
        int tempSum = new getData(getApplicationContext()).getSum();
        if (tempSum==0){
            tAVR.setText(Double.toString(0));
        }
        else {
            tAVR.setText(new DecimalFormat("##.##").format(tempAvr));
        }
        cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo._ID);
        sortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                    cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo._ID);
                    sortList(byYear,bySem);

                } else if (position == 1) {
                    cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.COURSE);
                    sortList(byYear,bySem);
                }
                else if (position == 2) {
                    cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.YEAR);
                    sortList(byYear,bySem);
                }
                else if (position == 3) {
                    cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.SEMESTER);
                    sortList(byYear,bySem);
                }
                else if (position == 4) {
                    cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.GRADE);
                    sortList(byYear,bySem);
                }
                else if (position == 5) {
                    cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.POINTS);
                    sortList(byYear,bySem);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        listView = (ListView) findViewById(R.id.list_view);
        View header = getLayoutInflater().inflate(R.layout.header, null);
        listView.addHeaderView(header);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("XXXXXXXXXXXXXXX");
        AdRequest adRequest = new AdRequest.Builder()
                .build();

        mInterstitialAd.loadAd(adRequest);
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
        AdView mAdView = (AdView) findViewById(R.id.adView);

        mAdView.loadAd(adRequest);
    }
    public static int getLocationSpinner(String arr[], String a){
        int loc=-1;
        for (int i=0;i<arr.length;i++){
            if (arr[i].equals(a)){
                loc=i;
            }
        }
        return loc;
    }
    public void sortList(String byYear,String bySem){
        registerForContextMenu(listView);
        listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
        listView.setAdapter(listDataAdaptar);
        ImageButton button= (ImageButton) findViewById(R.id.settingsButton);

        if (!cursor.moveToFirst()){
        }
        else {

            do {
                String year,semester,course,points,grade;
                year = cursor.getString(0);
                semester = cursor.getString(1);
                course = cursor.getString(2);
                points = cursor.getString(3);
                grade = cursor.getString(4);
                butt
                addTheCourse(year, semester, course, points, grade,button);
            }
            while (cursor.moveToNext());
        }

    }
    public void addTheCourse(String year,String semester,String course,String points,String grade,ImageButton but){
        DataProvider dataProvider = new DataProvider(year, semester, course, points, grade,but);
        listDataAdaptar.add(dataProvider);
    }
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        if (((AdapterView.AdapterContextMenuInfo)menuInfo).position == 0) {
            return;
        }
        inflater.inflate(R.menu.menu_data_list, menu);
        menu.setHeaderTitle("Options");
    }
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info =
                (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        final int mySelectedRowIndex = info.position-1;
        com.grade.ido.grades.DataProvider raw2 = (com.grade.ido.grades.DataProvider) listDataAdaptar.getItem(mySelectedRowIndex);

            switch (item.getItemId()) {
                case R.id.update_item:
                   //case 1 code .....
                    return true;
                case R.id.delete_item:
                   //case 2 code .....
                    return true;
                case R.id.change_grade:
                   //case 3 code .....
                    return super.onOptionsItemSelected(item);
            }

        }

    public void onBackPressed() {
        startActivity(new Intent(this, MainActivity.class));
    }

    private void hideActionBar() {
        //Hide the action bar only if it exists
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
    }
    }

这是我的ListDataAdapter.java

package com.grade.ido.grades;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.grade.ido.grades.*;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ido on 08/08/2015.
 */
public class ListDataAdaptar extends ArrayAdapter{
        List list = new ArrayList();
    SQLiteDatabase sqLiteDatabase;
    com.grade.ido.grades.CourseDbHelper courseDbHelper;

    public ListDataAdaptar(Context context, int resource) {

        super(context, resource);

    }
    static class LayoutHandler{
        TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
        ImageButton BUTTON;
    }
    @Override
    public void add(Object object) {
        super.add(object);
        list.add(object);
    }
    @Override
    public int getCount() {
        return list.size();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        LayoutHandler layoutHandler;
        if (row == null){
            LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row  = layoutInflater.inflate(com.grade.ido.grades.R.layout.row_layout,parent,false);
            layoutHandler = new LayoutHandler();
            layoutHandler.YEAR = (TextView)row.findViewById(com.grade.ido.grades.R.id.textYear);
            layoutHandler.SEMESTER = (TextView)row.findViewById(com.grade.ido.grades.R.id.textSemester);
            layoutHandler.COURSE = (TextView)row.findViewById(com.grade.ido.grades.R.id.textCourse);
            layoutHandler.POINTS = (TextView)row.findViewById(com.grade.ido.grades.R.id.textPoints);
            layoutHandler.GRADE = (TextView)row.findViewById(com.grade.ido.grades.R.id.textGrade);
            layoutHandler.BUTTON= (ImageButton) row.findViewById(R.id.settingsButton);
            row.setTag(layoutHandler);
        }
        else{
            layoutHandler = (LayoutHandler) row.getTag();

        }
        final com.grade.ido.grades.DataProvider dataProvider = (com.grade.ido.grades.DataProvider) this.getItem(position);
        layoutHandler.YEAR.setText(dataProvider.getYear());
        layoutHandler.SEMESTER.setText(dataProvider.getSemester());
        layoutHandler.COURSE.setText(dataProvider.getCourse());
        layoutHandler.POINTS.setText(dataProvider.getPoints());
        layoutHandler.GRADE.setText(dataProvider.getGrade());
   //     layoutHandler.BUTTON.setOnClickListener(new View.OnClickListener() {
  //        @Override
  //         public void onClick(View view) {
  //             ContextMenu cm;
  //
  //              Toast.makeText(getContext(), dataProvider.getCourse(),
  //                      Toast.LENGTH_LONG).show();
            }
        });
        return row;
}

}

row_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">
    <TextView
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:id="@+id/textGrade"
        android:text="Grade"
        android:gravity="center"
        android:textColor="#000000"/>
    <TextView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:id="@+id/textPoints"
        android:text="Points"
        android:gravity="center"
        android:textColor="#000000"/>
    <TextView
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:id="@+id/textCourse"
        android:text="Course"
        android:gravity="center"
        android:textColor="#000000"/>
    <TextView
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:id="@+id/textSemester"
        android:text="Semester"
        android:gravity="center"
        android:textColor="#000000"/>
    <TextView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:id="@+id/textYear"
        android:text="Year"
        android:gravity="center"
        android:textColor="#000000"/>
    <ImageButton
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:id="@+id/settingsButton"
        android:src="@drawable/settings"
        android:nestedScrollingEnabled="false" />
</LinearLayout>

0 个答案:

没有答案