在视图上添加按钮

时间:2013-02-27 18:58:04

标签: java android user-interface

我为此疯狂。

我没有找到任何可行的解决方案(尝试了一些来自stackoverflow)

场景(这是已经完成的实际屏幕截图):

enter image description here

我有一个以视图为属性的活动。

此视图通过View.addView(myView)添加另一个视图。

我现在想要在myView中添加一个Button(具体来说:在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(也许这就是我的思维障碍),而是动态设置按钮属性。

任何提示都表示赞赏!

2 个答案:

答案 0 :(得分:1)

您希望扩展ViewGroup而不仅仅是View(LinearLayout,RelativeLayout,FrameLayout等) - 它们会为您处理子视图。

答案 1 :(得分:0)

我想也许您需要刷新整个视图/活动。尝试在onResume方法中执行此操作,也许这会有所帮助。但是因为你没有使用layout.xml,我不确定这对你有多大帮助..

@Override
protected void onResume(){
super.onResume();
setContentView(R.layout.activity_main);
}
相关问题