[英]How to create a Checkbox object in Android Studio with its own Action Listener
I already did it on java on which the JCheckbox object has it's own Action Listener and characteristics, here is a sample code in java..我已经在 java 上做过,JCheckbox object 有它自己的动作监听器和特性,这里是 java 中的示例代码。
private class checkBoxTask extends JCheckBox{
checkBoxTask me;
public checkBoxTask(){
super();
me = this;
me.setText("task");
}
}
But at Android Studio, I'm getting a 'super(Context context)' constructor that gave an error on adding the checkbox in the layout because i need to pass an argument value on it which is i don't know what.但是在 Android Studio 中,我得到一个“超级(上下文上下文)”构造函数,在布局中添加复选框时出错,因为我需要在其上传递一个参数值,我不知道是什么。
class task extends androidx.appcompat.widget.AppCompatCheckBox {
task me;
public task(Context context) {
super(context);
me=this;
me.setText("task");
}
}
FloatingActionButton newTask = findViewById(R.id.newTask);
newTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LinearLayout taskLayout = findViewById(R.id.taskLayout);
taskLayout.addView(new task()); //<-- here is where the
code wants me to put an argument
logValue++;
}
});
Im still new to this, I'd like to know what can I do in that constructor我还是新手,我想知道在那个构造函数中我能做什么
It looks like you need to pass a Context argument (https://developer.android.com/reference/android/content/Context ).看起来您需要传递一个Context参数(https://developer.android.com/reference/android/content/Context )。
For example in fragment, you should get it like this:例如在片段中,你应该这样得到它:
Context mContext; // global variable
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mContext = context;
}
Or you can simply do this:或者你可以简单地这样做:
taskLayout.addView(new task(getContext));
I figured it out now.我现在想通了。 thanks for Etoile., I just pass the java class name as the context.
感谢 Etoile。我只是通过 java class 名称作为上下文。 here..
这里..
public void onClick(View view) { public void onClick(查看视图){
LinearLayout taskLayout = findViewById(R.id.taskLayout);
taskLayout.addView(new task(MainActivity.this));
logValue++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.