添加的onClick侦听器的GridView项目(推出独特的意图取决于所处的位置)侦听器、所处、意图、独特

2023-09-05 04:54:31 作者:半成品

我有一个GridView,我想推出一个不同的意图取决于项目的位置点击。

我已经实例以下的onClick监听器,包括位置值:

  gridview.setOnItemClickListener(新OnItemClickListener(){
    公共无效onItemClick(适配器视图<>母公司,视图V,INT位置,长的id){
        Toast.makeText(HelloGridView.this,+位置,Toast.LENGTH_SHORT).show();
    }
});
 

不过,我相信我会需要添加一个,如果在它的语句,以确定哪些意图取决于这个位置推出。到目前为止,我想出了以下,但我不相信这是我在寻找什么。

 如果位置= 1 {意向意图=新的意图(这一点,Activity1.class); }否则,如果位置= 2 {意向意图=新的意图(这一点,Activity1.class); }
 

任何建议都大大AP preciated。

/ **  *此活动presents与栅在屏幕上的影像,可以添加和  *搬来搬去。它还定义在画面上的区域,其中拖次能  *被丢弃。反馈提供给用户作为对象拖过  *这些放置区。  *  *

 *就像在DragView例的previous版本DragActivity  *应用程序中,code下面是Android的启动code来源。  *  *

 *原始启动code需要长按(preSS)来启动  *拖放序列。如果你想看到的行为,设置变量  * mLongClickStartsDrag为true。它被设置为低于假,这意味着,任何  *触摸事件开始拖放。  *  * /

 公共类DragActivity扩展活动实现View.OnLongClickListener,
View.OnClickListener,View.OnTouchListener //,
// AdapterView.OnItemClickListener
{

    / **
     * /
    //常量

    私有静态最终诠释HIDE_TRASHCAN_MENU_ID = Menu.FIRST;
    私有静态最终诠释SHOW_TRASHCAN_MENU_ID = Menu.FIRST + 1;
    私有静态最终诠释ADD_OBJECT_MENU_ID = Menu.FIRST + 2;
    私有静态最终诠释CHANGE_TOUCH_MODE_MENU_ID = Menu.FIRST + 3;
    私人布尔isErase = TRUE;
    私人的EditText等;
    私人TextView的TX;

    / **
     * /
    //变量

    私人的DragController mDragController; //对象处理拖放
    // 序列。它intersacts与
    //的DragSource和DropTarget的
    //对象。
    私人DragLayer mDragLayer; //该的ViewGroup在其中一个对象可以是
    //拖动。
    私人DeleteZone mDeleteZone; //用于去除放置目标
    //从屏幕上的对象。
    私人诠释mImageCount = 0; //图像的已添加到数
    // 屏幕。
    私人的ImageCell mLastNewCell = NULL; //最后的ImageCell加入到
    //添加图像被点击时的屏幕。
    私人布尔mLongClickStartsDrag = TRUE; //如果为真,这需要很长
    //点​​击开始拖动
    //操作。
    //否则,任何触摸
    //事件开始拖累。

    公共静态最终布尔调试=假; //使用这个看多
    //敬酒的消息。

    / **
     * /
    //方法

    / **
     *添加一个新的形象,使用户可以移动它。它显示在
     *屏幕image_source_frame一部分。
     *
     * @参数RESOURCEID
     * int  - 要添加的图像的资源ID
     * /

    公共无效addNewImageToScreen(INT RESOURCEID){
        如果(mLastNewCell!= NULL)
            mLastNewCell.setVisibility(View.GONE);

        的FrameLayout imageHolder的=(的FrameLayout)findViewById(R.id.image_source_frame);
        如果(imageHolder的!= NULL){
            FrameLayout.LayoutParams LP =新FrameLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,
                    Gravity.CENTER);
            的ImageCell NewView的=新的ImageCell(本);
            newView.setImageResource(RESOURCEID);
            imageHolder.addView(NewView的,LP);
            newView.mEmpty = FALSE;
            newView.mCellNumber = -1;
            mLastNewCell = NewView的;
            mImageCount ++;

            //有这个活动听触摸和点击事件的看法。
            newView.setOnClickListener(本);
            newView.setOnLongClickListener(本);
            newView.setOnTouchListener(本);

        }
    }

    / **
     *添加图像之一的屏幕,以便用户有一个新的图像移动
     * 周围。见addImageToScreen。
     *
     * /

    公共无效addNewImageToScreen(){
        INT RESOURCEID = R.drawable.sqwhite;
        addNewTextToScreen();
        INT M = mImageCount%3;

        如果(米== 1)
            RESOURCEID = R.drawable.sqdrk;

        否则,如果(米== 2)
            RESOURCEID = R.drawable.sqwhite;
        addNewImageToScreen(RESOURCEID);

    }

    私人无效addNewTextToScreen(){
        // TODO自动生成方法存根

    // et.setVisibility(View.VISIBLE);
        如果(isErase){
            tx.setText(et.getText()的toString());
        } 其他 {
            tx.setText();
            et.setVisibility(View.GONE);
        }
        isErase = isErase!;
    }

    / **
     *处理视图上点击。
     *
     * /

    公共无效的onClick(视图v){
        如果(mLongClickStartsDrag){
            //告诉它需要很长的点击开始拖动用户。
            //吐司(preSS不放拖动图像。);


        }
    }

    / **
     *手柄的添加图像按钮的点击
     *
     * /

    公共无效onClickAddImage(视图v){
        addNewImageToScreen();
    }

    / **
     *的onCreate  - 被称为第一次创建活动时。
     *
     *创建一拖控制器,并设置了三个意见,点击并长按
     *对意见发送到这项活动。该onLongClick方法启动
     *阻力序列。
     *
     * /

    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        的setContentView(R.layout.demo);
        等=(EditText上)findViewById(R.id.editText1);
        et.setVisibility(View.INVISIBLE);
        TX =(TextView中)findViewById(R.id.textView1);

        GridView控件的GridView =(GridView控件)findViewById(R.id.image_grid_view);

        如果(GridView的== NULL)
            吐司(无法找到GridView控件);
        其他 {
            gridView.setAdapter(新ImageCellAdapter(本));
            // gridView.setOnItemClickListener(本);
        }

        mDragController =新的DragController(本);
        mDragLayer =(DragLayer)findViewById(R.id.drag_layer);
        mDragLayer.setDragController(mDragController);
        mDragLayer.setGridView(GridView的);

        mDragController.setDragListener(mDragLayer);
        // mDragController.addDropTarget(mDragLayer);

        mDeleteZone =(DeleteZone)findViewById(R.id.delete_zon​​e_view);

        //给用户一些指导。
        Toast.makeText(getApplicationContext(),
                getResources()的getString(R.string.instructions)
                Toast.LENGTH_LONG).show();
    }

    / **
     *建立了活动的菜单。
     *
     * /

    公共布尔onCreateOptionsMenu(功能菜单){
        super.onCreateOptionsMenu(菜单);

        menu.add(0,HIDE_TRASHCAN_MENU_ID,0,隐藏垃圾桶)。setShortcut('1',
                'C');
        menu.add(0,SHOW_TRASHCAN_MENU_ID,0,查看垃圾桶)。setShortcut('2',
                'C');
        menu.add(0,ADD_OBJECT_MENU_ID,0,添加视图)setShortcut('9','Z')。
        menu.add(0,CHANGE_TOUCH_MODE_MENU_ID,0,更改触摸模式);

        返回true;
    }

    / **
     *处理的项目在细胞的网格的点击。
     *
     * /

    公共无效onItemClick(适配器视图<>母公司,视图V,INT位置,长的id){
        的ImageCell I =(的ImageCell)V;
        跟踪(onItemClick的观点:+ i.mCellNumber);
    }

    / **
     *手柄很长的点击。如果mLongClick仅是真的,这将是唯一的
     *方式开始拖动操作。
     *
     * @参数v
     *            视图
     * @返回布尔值 - 真表示该事件已经被处理
     * /

    公共布尔onLongClick(视图v){
        如果(mLongClickStartsDrag){

            //跟踪(onLongClick的观点:+ V +TouchMode的:+
            // v.isInTouchMode());

            //确保阻力是由长preSS开始,而不是一个
            //长按。
            //(注:我在Android得到这个从工作区对象
            //启动code。
            //我认为这是在这里,以确保设备仍然在触摸
            //模式,当我们开始拖动操作。)
            如果(!v.isInTouchMode()){
                吐司(isInTouchMode返回false再次尝试触及的观点。);
                返回false;
            }
            返回的startDrag(五);
        }

        //如果我们来到这里,返回false以表明我们没有照顾
        //事件。
        返回false;
    }

    / **
     *响应菜单项被点击执行操作。
     *
     * /

    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
        案例HIDE_TRASHCAN_MENU_ID:
            如果(mDeleteZone!= NULL)
                mDeleteZone.setVisibility(View.INVISIBLE);
            返回true;
        案例SHOW_TRASHCAN_MENU_ID:
            如果(mDeleteZone!= NULL)
                mDeleteZone.setVisibility(View.VISIBLE);
            返回true;
        案例ADD_OBJECT_MENU_ID:
            //添加一个新的对象到屏幕上;
            addNewImageToScreen();
            返回true;
        案例CHANGE_TOUCH_MODE_MENU_ID:
            mLongClickStartsDrag = mLongClickStartsDrag!;
            字符串消息= mLongClickStartsDrag? 更改触摸模式。现在拖上开始长触摸(点击)。
                    :变化的触摸模式拖动现在开始触摸(点击)。;
            Toast.makeText(getApplicationContext(),消息,Toast.LENGTH_LONG)
            。显示();
            返回true;
        }

        返回super.onOptionsItemSelected(项目);
    }

    / **
     *这是起点拖动操作,如果mLongClickStartsDrag
     *是假的。它寻找获取生成当用户在关闭事件
     *触摸屏。只有启动拖放序列。
     *
     * /

    公共布尔onTouch(视图V,MotionEvent EV){
        //如果我们被配置为只在长按开始,我们不打算
        //在这里处理任何事件。
        如果(mLongClickStartsDrag)
            返回false;

        布尔handledHere = FALSE;

        最终诠释行动= ev.getAction();

        //当开始拖动一个长按是没有必要的情况下,
        //只需启动的关闭事件。
        如果(动作== MotionEvent.ACTION_DOWN){
            handledHere =的startDrag(V);
        }

        返回handledHere;
    }

    / **
     *开始拖动一个视图。
     *
     * /

    公共布尔的startDrag(视图v){
        DragSource上的DragSource =(DragSource上)V;

        //我们已经开始拖累。让的DragController处理。
        mDragController.startDrag(V,DragSource上,DragSource上,
                DragController.DRAG_ACTION_MOVE);

        返回true;
    }

    / **
     *通过显示敬酒在屏幕上的字符串。
     *
     * @参数味精
     *            串
     * @返回无效
     * /

    公共无效吐司(弦乐味精){
        Toast.makeText(getApplicationContext(),味精,Toast.LENGTH_SHORT).show();
    } //结束敬酒

    / **
     *发送消息到调试日志。用吐司如果调试也显示它
     * 是真的。
     * /

    公共无效跟踪(弦乐味精){
        Log.d(DragActivity,味精);
        如果(!调试)
            返回;
        吐司(MSG);
    }

} //结束类
 
1人撒谎,致4000人隔离 1人隐瞒,68名医务者被隔离 故意传播突发传染病病原体,最高判死刑 武汉

解决方案

从Android文档GridView的:

  gridview.setOnItemClickListener(新OnItemClickListener(){
    公共无效onItemClick(适配器视图<>母公司,视图V,INT位置,长的id){
        Toast.makeText(HelloGridView.this,+位置,Toast.LENGTH_SHORT).show();
    }
});
 

编辑: 它看起来像addNewImageToScreen()是您要添加的ImageCells,所以假设你可以生成该范围的意图。

 意向意图=新的意图(这一点,Activity1.class); //或任何你想要运行
的ImageCell NewView的= ...
newView.setTag(意向);
 

然后在您的onItemClick:     公共无效onItemClick(适配器视图父,视图V,INT位置,长的id){         Toast.makeText(HelloGridView.this,+位置,Toast.LENGTH_SHORT).show();         意向意图=(意向)v.getTag();         //现在你可以用你的意图startActivity ..     }

I have a gridView and I'd like to launch a different intent depending on the position of the item clicked.

I've instantiated the following onClick listener which includes the value for position:

gridview.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
    }
});

But I believe I'll need to add an if statement within it to determine which intent to launch depending on this position. So far I've come up with the following but I do not believe it is exactly what I'm looking for.

if position = 1 { Intent intent = new Intent(this, Activity1.class); }else if position = 2 { Intent intent = new Intent(this, Activity1.class); }

Any suggestions are greatly appreciated.

/** * This activity presents a screen with a grid on which images can be added and * moved around. It also defines areas on the screen where the dragged views can * be dropped. Feedback is provided to the user as the objects are dragged over * these drop zones. * *

* Like the DragActivity in the previous version of the DragView example * application, the code here is derived from the Android Launcher code. * *

* The original Launcher code required a long click (press) to initiate a * drag-drop sequence. If you want to see that behavior, set the variable * mLongClickStartsDrag to true. It is set to false below, which means that any * touch event starts a drag-drop. * */

public class DragActivity extends Activity implements View.OnLongClickListener,
View.OnClickListener, View.OnTouchListener // ,
// AdapterView.OnItemClickListener
{

    /**
     */
    // Constants

    private static final int HIDE_TRASHCAN_MENU_ID = Menu.FIRST;
    private static final int SHOW_TRASHCAN_MENU_ID = Menu.FIRST + 1;
    private static final int ADD_OBJECT_MENU_ID = Menu.FIRST + 2;
    private static final int CHANGE_TOUCH_MODE_MENU_ID = Menu.FIRST + 3;
    private boolean isErase = true;
    private EditText et;
    private TextView tx;

    /**
     */
    // Variables

    private DragController mDragController; // Object that handles a drag-drop
    // sequence. It intersacts with
    // DragSource and DropTarget
    // objects.
    private DragLayer mDragLayer; // The ViewGroup within which an object can be
    // dragged.
    private DeleteZone mDeleteZone; // A drop target that is used to remove
    // objects from the screen.
    private int mImageCount = 0; // The number of images that have been added to
    // screen.
    private ImageCell mLastNewCell = null; // The last ImageCell added to the
    // screen when Add Image is clicked.
    private boolean mLongClickStartsDrag = true; // If true, it takes a long
    // click to start the drag
    // operation.
    // Otherwise, any touch
    // event starts a drag.

    public static final boolean Debugging = false; // Use this to see extra
    // toast messages.

    /**
     */
    // Methods

    /**
     * Add a new image so the user can move it around. It shows up in the
     * image_source_frame part of the screen.
     * 
     * @param resourceId
     *            int - the resource id of the image to be added
     */

    public void addNewImageToScreen(int resourceId) {
        if (mLastNewCell != null)
            mLastNewCell.setVisibility(View.GONE);

        FrameLayout imageHolder = (FrameLayout) findViewById(R.id.image_source_frame);
        if (imageHolder != null) {
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                    Gravity.CENTER);
            ImageCell newView = new ImageCell(this);
            newView.setImageResource(resourceId);
            imageHolder.addView(newView, lp);
            newView.mEmpty = false;
            newView.mCellNumber = -1;
            mLastNewCell = newView;
            mImageCount++;

            // Have this activity listen to touch and click events for the view.
            newView.setOnClickListener(this);
            newView.setOnLongClickListener(this);
            newView.setOnTouchListener(this);

        }
    }

    /**
     * Add one of the images to the screen so the user has a new image to move
     * around. See addImageToScreen.
     * 
     */

    public void addNewImageToScreen() {
        int resourceId = R.drawable.sqwhite;
        addNewTextToScreen();
        int m = mImageCount % 3;

        if (m == 1)
            resourceId = R.drawable.sqdrk;

        else if (m == 2)
            resourceId = R.drawable.sqwhite;
        addNewImageToScreen(resourceId);

    }

    private void addNewTextToScreen() {
        // TODO Auto-generated method stub

    //  et.setVisibility(View.VISIBLE);
        if (isErase) {
            tx.setText(et.getText().toString());
        } else {
            tx.setText("");
            et.setVisibility(View.GONE);
        }
        isErase = !isErase;
    }

    /**
     * Handle a click on a view.
     * 
     */

    public void onClick(View v) {
        if (mLongClickStartsDrag) {
            // Tell the user that it takes a long click to start dragging.
            //toast("Press and hold to drag an image.");


        }
    }

    /**
     * Handle a click of the Add Image button
     * 
     */

    public void onClickAddImage(View v) {
        addNewImageToScreen();
    }

    /**
     * onCreate - called when the activity is first created.
     * 
     * Creates a drag controller and sets up three views so click and long click
     * on the views are sent to this activity. The onLongClick method starts a
     * drag sequence.
     * 
     */

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.demo);
        et = (EditText) findViewById(R.id.editText1);
        et.setVisibility(View.INVISIBLE);
        tx = (TextView) findViewById(R.id.textView1);

        GridView gridView = (GridView) findViewById(R.id.image_grid_view);

        if (gridView == null)
            toast("Unable to find GridView");
        else {
            gridView.setAdapter(new ImageCellAdapter(this));
            // gridView.setOnItemClickListener (this);
        }

        mDragController = new DragController(this);
        mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
        mDragLayer.setDragController(mDragController);
        mDragLayer.setGridView(gridView);

        mDragController.setDragListener(mDragLayer);
        // mDragController.addDropTarget (mDragLayer);

        mDeleteZone = (DeleteZone) findViewById(R.id.delete_zone_view);

        // Give the user a little guidance.
        Toast.makeText(getApplicationContext(),
                getResources().getString(R.string.instructions),
                Toast.LENGTH_LONG).show();
    }

    /**
     * Build a menu for the activity.
     * 
     */

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, HIDE_TRASHCAN_MENU_ID, 0, "Hide Trashcan").setShortcut('1',
                'c');
        menu.add(0, SHOW_TRASHCAN_MENU_ID, 0, "Show Trashcan").setShortcut('2',
                'c');
        menu.add(0, ADD_OBJECT_MENU_ID, 0, "Add View").setShortcut('9', 'z');
        menu.add(0, CHANGE_TOUCH_MODE_MENU_ID, 0, "Change Touch Mode");

        return true;
    }

    /**
     * Handle a click of an item in the grid of cells.
     * 
     */

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        ImageCell i = (ImageCell) v;
        trace("onItemClick in view: " + i.mCellNumber);
    }

    /**
     * Handle a long click. If mLongClick only is true, this will be the only
     * way to start a drag operation.
     * 
     * @param v
     *            View
     * @return boolean - true indicates that the event was handled
     */

    public boolean onLongClick(View v) {
        if (mLongClickStartsDrag) {

            // trace ("onLongClick in view: " + v + " touchMode: " +
            // v.isInTouchMode ());

            // Make sure the drag was started by a long press as opposed to a
            // long click.
            // (Note: I got this from the Workspace object in the Android
            // Launcher code.
            // I think it is here to ensure that the device is still in touch
            // mode as we start the drag operation.)
            if (!v.isInTouchMode()) {
                toast("isInTouchMode returned false. Try touching the view again.");
                return false;
            }
            return startDrag(v);
        }

        // If we get here, return false to indicate that we have not taken care
        // of the event.
        return false;
    }

    /**
     * Perform an action in response to a menu item being clicked.
     * 
     */

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case HIDE_TRASHCAN_MENU_ID:
            if (mDeleteZone != null)
                mDeleteZone.setVisibility(View.INVISIBLE);
            return true;
        case SHOW_TRASHCAN_MENU_ID:
            if (mDeleteZone != null)
                mDeleteZone.setVisibility(View.VISIBLE);
            return true;
        case ADD_OBJECT_MENU_ID:
            // Add a new object to the screen;
            addNewImageToScreen();
            return true;
        case CHANGE_TOUCH_MODE_MENU_ID:
            mLongClickStartsDrag = !mLongClickStartsDrag;
            String message = mLongClickStartsDrag ? "Changed touch mode. Drag now starts on long touch (click)."
                    : "Changed touch mode. Drag now starts on touch (click).";
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
            .show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * This is the starting point for a drag operation if mLongClickStartsDrag
     * is false. It looks for the down event that gets generated when a user
     * touches the screen. Only that initiates the drag-drop sequence.
     * 
     */

    public boolean onTouch(View v, MotionEvent ev) {
        // If we are configured to start only on a long click, we are not going
        // to handle any events here.
        if (mLongClickStartsDrag)
            return false;

        boolean handledHere = false;

        final int action = ev.getAction();

        // In the situation where a long click is not needed to initiate a drag,
        // simply start on the down event.
        if (action == MotionEvent.ACTION_DOWN) {
            handledHere = startDrag(v);
        }

        return handledHere;
    }

    /**
     * Start dragging a view.
     * 
     */

    public boolean startDrag(View v) {
        DragSource dragSource = (DragSource) v;

        // We are starting a drag. Let the DragController handle it.
        mDragController.startDrag(v, dragSource, dragSource,
                DragController.DRAG_ACTION_MOVE);

        return true;
    }

    /**
     * Show a string on the screen via Toast.
     * 
     * @param msg
     *            String
     * @return void
     */

    public void toast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    } // end toast

    /**
     * Send a message to the debug log. Also display it using Toast if Debugging
     * is true.
     */

    public void trace(String msg) {
        Log.d("DragActivity", msg);
        if (!Debugging)
            return;
        toast(msg);
    }

} // end class

解决方案

from the android documentation for GridView:

gridview.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
    }
});

edit: It looks like the addNewImageToScreen() is where you are adding the ImageCells, so assuming that you can generate the intent in that scope..

Intent intent = new Intent(this, Activity1.class); // or whatever you want to run
ImageCell newView = ...
newView.setTag( intent );

then in your onItemClick: public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show(); Intent intent = (Intent) v.getTag(); // now you can startActivity with your intent.. }