2013-09-25 32 views
1

我正在動態創建LinearLayout。我需要刪除LinearLayout上的LongPress事件。在長按事件上刪除LinearLayout

我的代碼:

public void addTileView(View v) {   
     _parentLayout = (LinearLayout) findViewById(R.id.gridCont); 

    View child = getLayoutInflater().inflate(R.layout.customtileview,null); 
    ((TextView)child.findViewById(R.id.tileText)).setText("Tile View :"+_tileViewCount++);  
    _parentLayout.addView(child);  
    _parentLayout.setOnLongClickListener(new OnLongClickListener() { 
     @Override 
     public boolean onLongClick(View v) { 
      // TODO Auto-generated method stub 
      Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_SHORT).show(); 

      return true; 
     } 
    }); 

} 

如何做到這一點?

回答

0

這適用於我。

public void addTileView(View v) { 

     _parentLayout = (LinearLayout) findViewById(R.id.gridCont); 

     child = getLayoutInflater().inflate(R.layout.customtileview,null); 
    ((TextView)child.findViewById(R.id.tileText)).setText("Tile View :"+_tileViewCount++); 



    _parentLayout.addView(child); 

    child.setOnLongClickListener(new OnLongClickListener() { 
     @Override 
     public boolean onLongClick(View v) { 
      // TODO Auto-generated method stub 
      Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_SHORT).show(); 
      _parentLayout.removeView(v); 
      return true; 
     } 
    }); 



} 

感謝

3

試試這個,

_parentLayout.setOnLongClickListener(new OnLongClickListener() { 
    @Override 
    public boolean onLongClick(View v) { 
     // TODO Auto-generated method stub 
     Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_SHORT).show(); 

      parentLayout.removeAllViews(); 
     return true; 
    } 
}); 
+0

它將刪除父也。我需要刪除在哪個longpress事件觸發的指定視圖。 – tilak

+0

child.removeAllViews()我不會沒有它會工作與否。去嘗試一下。我希望它會起作用 –

2

其更好地刪除您在父添加的視圖。 說父佈局是主佈局,子佈局是您想要刪除的佈局。 您應該嘗試 parent_layout.removeView(child_layout);

removeAllViews() - 將刪除視圖內的所有視圖,但不刪除主視圖。

請參考ViewGroup ViewGroup vg =(ViewGroup)(myView.getParent()); vg.removeView(myView);

或者,您可以將視圖的可見性設置爲Visible.GONE,然後在需要時使其可見。