activity_levels.xml
<Button
android:id="@+id/level2"
android:layout_width="100dp"
android:layout_height="105dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="200dp"
android:layout_marginEnd="130dp"
android:layout_marginRight="198dp"
android:background="#FF0000"
android:text="2"
android:textSize="40sp"
android:enabled="false" />
Levels.java
public class Levels extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_levels);
}
}
activity_level_one_result.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Next Level"
android:textAllCaps="false"
android:onClick="nextLevel"/>
LevelOneResult.java
public class LevelOneResult extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_one_result);
}
public void nextLevel(View view) {
startActivity(new Intent(getApplicationContext(), Levels.class));
// enable the button here
}
}
我想启用activity_levels.xml
文件中的2级按钮。我希望通过在LevelOneResult.java
中使用Java来启用它。正如您在上面看到的,我在要放置代码的位置添加了注释部分。
答案 0 :(得分:1)
在您的LevelOneResult.java中创建一个interface
,如下所示,我在代码的注释中进行了解释:
public class LevelOneResult extends AppCompatActivity {
OnCompleteListener mListener;
//create an listener
public interface OnCompleteListener {
void onComplete(boolean enableOrNot);
}
//attach the listener in the activity
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
this.mListener = (OnCompleteListener)activity;
}
catch (final ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnCompleteListener");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_one_result);
}
public void nextLevel(View view) {
startActivity(new Intent(getApplicationContext(), Levels.class));
// enable the button here
here trigger the listener
//true means enable
mListener.onComplete(true);
}
}
在您的Levels.java
中,您需要实现interface
,从接口onComplete()
中获取数据并完成工作
public class Levels extends AppCompatActivity implements LevelOneResult.OnCompleteListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_levels);
}
public void onComplete(boolean enableOrNot ) {
// after the action in LevelOne
// the boolean trigger here..
//here the boolean is true,which u set in levelOneJava
if(enableOrNot){
//then do your stuff here
}
}
}