onOptionsItemSelected不起作用

时间:2015-07-20 17:24:22

标签: android listview

我有两个问题。首先是当我点击我设置的选项时没有任何反应,在这种情况下,它是添加项目的选项,将用户带到另一个活动,但是当我点击它时没有任何反应。我创建了一个调用相同活动的按钮,它正在工作。同样在listView中选择项目是不行的,应该有一个弹出窗口从listView和数据库中删除项目,但是没有。我会在这里找到一些帮助,如果有人可以建议我如何在listView中创建多个选项并计算检查了多少项this

所以这是我的MainActivity:

    public class MainActivity extends BaseActivity {

    // Declare variables
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private GroceryDbAdapter mDbHelper;

    Button addItem;
    private Toolbar toolbar;
    private ListView listView;

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

        FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);

         // inflate the custom activity layout
        LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);

        frameLayout.addView(activityView);

        // Setting toolbar
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setLogo(R.drawable.shopping_cart_logo);

        // Setting database and adapter
        mDbHelper = new GroceryDbAdapter(this);
        mDbHelper.open();

        // Locate ListView
        listView = (ListView) findViewById(R.id.list);

        // Locate button and initialization
        addItem = (Button) findViewById(R.id.add_item);
        addItem.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

            }
        });

        fillData();
    }

    @SuppressWarnings("deprecation")
    private void fillData() {
        Cursor itemsCursor =  mDbHelper.fetchAllItems();
        startManagingCursor(itemsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{GroceryDbAdapter.KEY_TITLE, GroceryDbAdapter.KEY_PRICE};

        // and an array of the fields we want to bind those fields to (in this case just title)
        int[] to = new int[]{R.id.title, R.id.price};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter items = 
            new SimpleCursorAdapter(this, R.layout.list_item_row, itemsCursor, from, to);
        listView.setAdapter(items);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, "Add Item");
        return true;
    }

    public boolean onOptionsItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                createItem();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, "Delete Item");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteItem(info.id);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createItem() {
        Intent i = new Intent(this, AddActivity.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, AddActivity.class);
        i.putExtra(GroceryDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }

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

这是我的AddActivity.java,当用户从菜单(不工作)和按钮(工作正常)点击addItem时应该调用它:

    public class AddActivity extends BaseActivity {

    private Long mRowId;
    private GroceryDbAdapter mDbHelper;
    private EditText title_edit;
    private EditText price_edit;
    private Button saveButton;

    private Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mDbHelper = new GroceryDbAdapter(this);
        mDbHelper.open();
        setContentView(R.layout.add_activity_layout);

        mDrawerToggle.setDrawerIndicatorEnabled(false);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        getSupportActionBar().setLogo(R.drawable.shopping_cart_logo);


        // Locate the EditText in add_activity_layout.xml
        title_edit = (EditText) findViewById(R.id.titleEdit);
        price_edit = (EditText) findViewById(R.id.priceEdit);

        mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(GroceryDbAdapter.KEY_ROWID);
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(GroceryDbAdapter.KEY_ROWID)
                                    : null;
        }

        populateFields();

        saveButton = (Button) findViewById(R.id.save);

        saveButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
                overridePendingTransition(R.anim.slide_in_back, R.anim.slide_out_back);
            }

        });

    }

    private void populateFields() {
        if (mRowId != null) {
            Cursor item = mDbHelper.fetchItem(mRowId);
            startManagingCursor(item);
            title_edit.setText(item.getString(
                    item.getColumnIndexOrThrow(GroceryDbAdapter.KEY_TITLE)));
            price_edit.setText(item.getString(
                    item.getColumnIndexOrThrow(GroceryDbAdapter.KEY_PRICE)));
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(GroceryDbAdapter.KEY_ROWID, mRowId);
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }

    private void saveState() {
        String title = title_edit.getText().toString();
        String price = price_edit.getText().toString();

        if (mRowId == null) {
            long id = mDbHelper.createItem(title, price);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateItem(mRowId, title, price);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
        }

        return super.onOptionsItemSelected(item);
    }

}

以下是我的MainActivity布局:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />

    <Button
        android:id="@+id/add_item"
        style="@style/MyCustomButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/add_button" />

    <ListView
        android:id="@+id/list"
        android:choiceMode="multipleChoice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/add_item"
        android:layout_below="@+id/relativeLayout"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/margin"
        android:divider="@color/list_divider_row"
        android:dividerHeight="@dimen/divider_height"
        android:listSelector="@drawable/list_row_selector" >

    </ListView>

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_alignStart="@+id/listView1"
        android:layout_alignRight="@+id/listView1"
        android:layout_alignEnd="@+id/listView1"
        android:layout_below="@+id/app_bar"
        android:padding="@dimen/relative_layout_padding" >

        <TextView
            android:id="@+id/item_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dp"
            android:text="Items"
            android:textColor="#474747"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/item_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="4dp"
            android:layout_toRightOf="@+id/item_text"
            android:text="(2)"
            android:textColor="#474747"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/total_amount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="Rs. 5700"
            android:textColor="#000000"
            android:textSize="20dp" />

    </RelativeLayout>

</RelativeLayout>

修改

我的BaseActivity代码:

    package com.dusandimitrijevic.grocerylist;

import java.util.ArrayList;

import com.dusandimitrijevic.adapters.NavDrawerListAdapter;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public abstract class BaseActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    public ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_layout);

        mTitle = mDrawerTitle = getTitle();

     // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

     // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

     // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Shop
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Calendar
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Settings
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // About
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));

     // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);


        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name
        ){
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            switch (position) {
                case 0: {
                    Intent intent = new Intent(BaseActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                }
                case 1: {
                    Intent intent = new Intent(BaseActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                }
                case 2: {
                    Intent intent = new Intent(BaseActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                }
                case 3: {
                    Intent intent = new Intent(BaseActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                }
                case 4: {
                    Intent intent = new Intent(BaseActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                }
                default:
                    break;
            }
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /***
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_in_back, R.anim.slide_out_back);
    }

    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub

    }

}

1 个答案:

答案 0 :(得分:0)

而不是addItem.setOnClickListener,请使用listView.setOnItemClickListener

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(MainActivity.this, AddActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
    }
});

对于菜单项,请单击

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == DELETE_ID) {
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
            mDbHelper.deleteItem(info.id);
            fillData();
    }
    return true;
}