【问题标题】:onTouchListener detecting wrong dynamically created cardviewonTouchListener 检测错误的动态创建的卡片视图
【发布时间】:2017-08-15 19:26:26
【问题描述】:

我刚刚学会了如何动态创建卡片视图。我正在使用按钮来创建一个卡片视图,并且我已经将 onTouchListener 设置为它。当我只创建一张卡片时,onTouchListener 工作正常,但是一旦我再创建一张卡片,onTouchListener 就无法按预期工作。当我有 2 张卡并尝试移动第一张卡时,它会移动第二张而不是第一张。

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

Context context;
ImageView imageView;
RelativeLayout relativeLayout;
static int pos=0;

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

    context=this;
    relativeLayout=(RelativeLayout)findViewById(R.id.rl_layout);

    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 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) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {

        CreateCardViewWithoutImageView();

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    return true;
}

public void CreateCardViewWithoutImageView(){

    final CardView cardview=new CardView(context);

    cardview.setId(++pos);
    cardview.setLayoutParams((new CardView.LayoutParams(600, 600)));
    cardview.setContentPadding(25,25,25,25);
    cardview.setCardBackgroundColor(Color.MAGENTA);

    relativeLayout.addView(cardview);

}

private final View.OnTouchListener mListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View card, MotionEvent event) {
        // The View (v) here is a CardView as the onTouchListener is set to it
        RelativeLayout.LayoutParams layoutParamsRL = (RelativeLayout.LayoutParams) ((CardView) card).getLayoutParams();
        float dx = 0, dy = 0, x = 0, y = 0;

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                card.bringToFront();
                dx = event.getRawX() - layoutParamsRL.leftMargin;
                dy = event.getRawY() - layoutParamsRL.topMargin;
            }
            break;
            case MotionEvent.ACTION_MOVE: {
                x = event.getRawX();
                y = event.getRawY();
                layoutParamsRL.leftMargin = (int) (x - dx);
                layoutParamsRL.topMargin = (int) (y - dy);
                card.setLayoutParams(layoutParamsRL);
            }
            break;
            case MotionEvent.ACTION_UP: {

            }
            break;
        }
        return true;
    }
};

}

【问题讨论】:

    标签: android android-cardview


    【解决方案1】:

    这是因为您的 cardview 变量是全局变量。所以每次你创建一个新的 CardView 时,它都会被替换,所以监听器总是使用最后一个创建的 CardView。 你应该这样做:

    // Note: By the way, you should NOT use a capital letter to name a function
    public void createCardViewWithoutImageView(){
    
        //CardView
        final CardView cardview = new CardView(context);
    
        //....
    
    }
    

    layoutParamsRL 也会遇到同样的问题,因为它也应该是本地的。

    编辑

        // Context context; // You don't need to store the context here as you are in the activity
    //    CardView cardview; // Don't need to be global
    //    RelativeLayout.LayoutParams layoutParamsRL; // Don't need to be global
        ImageView imageView;
        RelativeLayout relativeLayout;
        static int pos = 0; // Are you sure it needs to be a static field?
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
    //        context=this;
            relativeLayout = (RelativeLayout) findViewById(R.id.rl_layout);
    
            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 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) {
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
    
                createCardViewWithoutImageView();
    
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            return true;
        }
    
        public void createCardViewWithoutImageView() {
    
            //CardView
            CardView cardview = new CardView(MainActivity.this);
    
            cardview.setId(++pos);
            cardview.setLayoutParams((new CardView.LayoutParams(600, 600)));
            cardview.setContentPadding(25, 25, 25, 25);
            cardview.setCardBackgroundColor(Color.MAGENTA);
            cardview.setOnTouchListener(mListener);
    
            relativeLayout.addView(cardview);
        }
    
        private final View.OnTouchListener mListener = new View.OnTouchListener() {
    
            float dx, dy; // Moved outside the onTouch method in order to them to keep their value.
    
            @Override
            public boolean onTouch(View card, MotionEvent event) {
                Log.d("OnTouchListener", "don't touch me :p");
    
                // The View (v) here is a CardView as the onTouchListener is set to it
                RelativeLayout.LayoutParams layoutParamsRL = (RelativeLayout.LayoutParams) ((CardView) card).getLayoutParams();
                float x = 0, y = 0;
    
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        card.bringToFront();
                        dx = event.getRawX() - layoutParamsRL.leftMargin;
                        dy = event.getRawY() - layoutParamsRL.topMargin;
                    }
                    break;
                    case MotionEvent.ACTION_MOVE: {
                        x = event.getRawX();
                        y = event.getRawY();
                        layoutParamsRL.leftMargin = (int) (x - dx);
                        layoutParamsRL.topMargin = (int) (y - dy);
                        card.setLayoutParams(layoutParamsRL);
                    }
                    break;
                    case MotionEvent.ACTION_UP: {
    
                    }
                    break;
                }
                return true;
            }
        };
    

    【讨论】:

    • 如果我这样做,我就无法从该方法之外更改卡片属性,例如宽度、高度。有什么方法可以同时获得这两个功能?
    • 我已经编辑了我的答案。您只需要一个onTouchListener(我使用的是变量,但Activity 本身可以实现接口),因为侦听器使用的所有变量都是本地变量,因此所有CardView 都可以重用同一个侦听器。 (我认为您尚未发布活动的所有代码,因此可能需要进行一些调整)。仅供参考,拥有全局和/或静态的所有内容通常不是一个好主意。最好将事物封装在小函数中。 :)
    • 我已按照您的建议对我的代码进行了一些更改。但现在我的卡没有响应触摸。你能看看代码吗?感谢您指出我代码中的那些小错误,我会努力改进。
    • 您确定它没有响应吗? (我还没有测试我的代码)也许问题是因为dxdy 应该保持在侦听器之外(否则当ACTION_MOVE 被触发并且什么都不会移动时,该值始终为0)。在 onTouchListener 中放置断点或日志信息以查看它是否响应。我已经更新了代码
    • *不在侦听器之外,而是在 onTouch 方法之外。像 dxdy 一样保持他们的价值
    【解决方案2】:

    1- 变量是全局的,所以你需要在上面提到的内部方法中定义 2-您可以使用另一种方法轻松更改其属性,并将 cardview 对象作为参数传递给它 3-您可以保留全局对象来表示选定的卡片视图,因为在 touchevent 方法中会将触发事件的卡片视图分配给全局并用它做你想做的事情

    【讨论】:

    • 第二步和第三步我看不懂,能否发一些代码供参考?
    【解决方案3】:

    //创建全局对象以在分配新属性时根据需要使用它

    CardView selectedCardview;
    @Override
    protected void onCreate(Bundle savedInstanceState) { //....... }
    

    //将创建内部对象

    public void CreateCardViewWithoutImageView(){
        CardView cardview = new CardView(context);
        //Setting the default property u want:)
        cardview.setId(++pos);
        cardview.setLayoutParams((new CardView.LayoutParams(600, 600)));
        .......
        final CardView tempCardView=cardview;
        cardview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction())
            {
                case MotionEvent.ACTION_DOWN :
                {
                  selectedCardview=tempCardView;
                  .........and adding action as u want
                }
                 ........... add another cases 
            }
    
        }
        ...........
    }
    

    现在你使用的 selectedCardview 将代表你触摸它的 cardview,并且很容易将其属性设置为全局

    void setProperty(){
        /******** add what u want here********/
        selectedCardview.setBackgroundColor(Color.RED);
    }
    

    【讨论】:

    • 内部 Card 将是最终的,因此我们无法在 onTouchListener 中更改其值。如果我用 selectedCardView 初始化它的值,就会出现这个错误:“指定的孩子已经有一个父母。你必须先在孩子的父母上调用 removeView()。”
    • 这意味着我不能同时使用两个卡片视图。我还想动态更改卡片属性(使用搜索栏)。
    • 现在查看我的更新,我在 onTouch 中使用 temp final 变量分配给 cardview,然后在 Ontouch 方法中将该变量分配给全局变量,这将解决您的问题,别忘了投票?
    • @ahmedshaaban 当cardview 本身可能是final 时,为什么还需要tempCardView?并且侦听器设置为 CardView,因此 View v 已经是 CardView,因此您只需将其转换为 CardView。 (CardView innerCV = (CardView) v 类似的东西)
    猜你喜欢
    • 2020-12-05
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多