2013-02-27 106 views
0

我對此很感興趣。在視圖中添加一個按鈕

我沒有找到任何有效的解決方案(試圖從計算器等等)

方案(這是一個實際的截圖什麼已經完成):

enter image description here

我有了一個活動視圖作爲他的屬性。

此視圖增加經由View.addView(MyView的)另一視圖。

我現在想要一個按鈕添加到MyView的(要具體:後MotionEvent.ACTION_UP按鈕應該出現在右下角(這將啓動機器人驅動履帶))

這裏是一個我的代碼快捷鍵:

public class ModeRouting extends View { 
public ModeRouting(Context context) { 
    super(context); 
Button asuroStartButton = new Button(context) //does not work 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    int actionevent = event.getAction(); 
    if (actionevent == MotionEvent.ACTION_UP 
      || actionevent == MotionEvent.ACTION_CANCEL) { 
asuroStartButton.visible=true; 
view.add(asuroStartButton); 
    } 
    return true; 
} 
} 

和我的活動:

//in constructor 
contentView = (FrameLayout) findViewById(R.id.content); 
onClickListenerFacade(routingMode, route); 

//this removes all views from stack and places the new one on the view 
private void onClickListenerFacade(View v, final View target) { 
    v.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      contentView.removeAllViews(); 
      contentView.setBackgroundColor(0xff000000); 
      contentView.addView(target); 
      modeSelectorAnimation(); 
     } 
    }); 
} 

我想在我的mainactivity.xml創建一個按鈕,並在我的mainactivity實例。

我缺少一些點在這裏,但我不知道它。

因爲我的觀點是純粹的動態(沒有layout.xml)我不認爲我應該使用layout.xml(也許這是我的思維封鎖),而是動態地設置按鈕屬性。

任何提示表示讚賞!

+0

那麼問題是什麼? – Simon 2013-02-27 19:00:18

+0

我無法實例化一個按鈕,也不能添加一個按鈕。 我需要一個靜態xml來添加一個按鈕,我需要在哪裏實例化(mainactivity?)。不會靜態xml覆蓋/銷燬動態內容(例如使用setContentView(R.layout.xy)會破壞我的軌道嗎?) – Wandang 2013-02-27 19:01:35

+1

您不需要一個靜態xml按鈕。你可以使用類似於:Button sampleButton = new Button(context); – lokoko 2013-02-27 19:02:29

回答

1

你想擴展ViewGroup而不是一個視圖(LinearLayout,RelativeLayout,FrameLayout等) - 它們爲你處理子視圖。

+0

謝謝。現在我得到了this.addView(按鈕)功能。 唯一的問題是該按鈕不會出現。 我確實設置了width/heigth 200,200和visibility = true,而且還是frontof()。仍然不可見。要繼續嘗試 – Wandang 2013-02-27 19:15:57

+0

你延伸了什麼?你很可能想要擴展RelativeLayout。在這種情況下,您需要調用setLayoutParams()傳遞一個RelativeLayout.LayoutParams來指定您希望視圖所在的位置。 – 2013-02-27 21:42:39

+0

哦,那是問題所在。我從ViewGroup擴展。要明天解決,謝謝 – Wandang 2013-02-28 22:48:36

0

我想也許你需要刷新整個視圖/活動。嘗試在onResume方法中做到這一點,也許這有助於。但是,因爲您不使用layout.xml,我不確定這是否對您有很大幫助。

@Override 
protected void onResume(){ 
super.onResume(); 
setContentView(R.layout.activity_main); 
} 
+0

謝謝你的努力,但我不認爲這有幫助。使用您的建議將與從我的活動中刪除視圖相同。 – Wandang 2013-02-27 19:17:49