我怎样才能从视图中完成活动

时间:2013-07-14 11:42:19

标签: java android view

我有一个具有自定义视图的活动。

我必须添加活动结果:

    public class ActView extends Activity implements OnClickListener {
<...code...>
@Override
    protected void onCreate(Bundle savedInstanceState) {
    <...code...>
     layout = (LinearLayout) findViewById(R.id.chart_container);
        timelineview = new VDrawTimeLine(this,contentFull);
        timelineview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        timelineview.setBackgroundColor(0xffffffff);
        timelineview.setVisibility(View.VISIBLE);

        layout.addView(timelineview);

    <...code...>
    }
}

查看课程:

public class VDrawTimeLine extends View implements OnTouchListener{
<...code...>
public VDrawTimeLine(Context context, ArrayList<_MainData> contentFull) {
        super(context);
        this.con = context;
        this.content = contentFull;
        <...code...>
    }
}
@Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        finishFunction();//I need here finish event this activity result for ActView Activity.
        return true;
    }

finishFunction - 我必须在这里写一下完成ActView与父活动的结果吗?

我需要这样的事情:

Intent intent = new Intent();
    intent.putExtra(dataname, value);
    setResult(RESULT_OK,intent);
    finish();

2 个答案:

答案 0 :(得分:7)

由于您使用的Context是Activity的Activitys context, you can cast the view上下文,因此调用finish()。

例如:

private void finishFunction() {
   Activity activity = (Activity)getContext();
   activity.finish();
}

从设计角度来看,它可能不是最佳选择

答案 1 :(得分:0)

如何从Android Kotlin的MVVM数据绑定中的View Model类关闭活动。

您应该通过以下活动在View Model类中传递上下文/活动引用

private lateinit var registerViewModel: RegisterViewModel

在onCreate方法上初始化它

registerViewModel = RegisterViewModel(this)

RegisterViewModel类,该类扩展到BaseObservable()

在下面的代码中编写该代码,以在单击按钮时关闭活动

fun handleOnClick(view: View) {
        when (view.id) {
            R.id.registerBTN -> {
                val activity = context as Activity
                activity.finish()
            }
            else -> Toast.makeText(context, "To-DO", Toast.LENGTH_SHORT).show()
        }
    }

您可以在您的layout.xml文件中进行如下定义

<Button
                android:id="@+id/registerBTN"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:enabled="@{registerViewModel.isAllowRegister}"
                android:layout_marginVertical="32dp"
                android:text="@string/register"
                android:onClick="@{registerViewModel::handleOnClick}"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/passwordET" />