我开发了一个计数器应用程序,当用户在屏幕上点击时,它会递减-1,并且每次打开应用程序时默认计数器号都是100。现在,我放了一个编辑按钮,它应该更改默认计数器号,但只能显示在屏幕上,并且无法用Java代码实现。下面是Java代码和xml。
MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="5dp"
android:id="@+id/tap"
android:background=" #2471a3 ">
<TextView
android:id="@+id/tvcounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
android:text="100"
android:textStyle="bold"
android:gravity="center"
android:background="@drawable/shape"
android:textColor="#FFF"
android:textSize="55sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="@+id/btnedit"
android:text="Edit"
android:textColor="#FFF"
android:layout_marginLeft="135dp"
android:background=" #154360 "/>
MainActivity.Java
RelativeLayout tap;
int counter=100 ;
TextView tvcounter;
tvcounter = findViewById(R.id.tvcounter);
tap = findViewById(R.id.tap);
tap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (counter != 0)
counter--;
tvcounter.setText(Integer.toString(counter));
}
}
});
layout_dialog.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editnum"
android:hint="Enter the number"
android:textColor="#000"
android:textSize="20sp"
android:inputType="number"
android:layout_marginTop="20dp"/>
ExampleDialog.Java
public class ExampleDialog extends AppCompatDialogFragment {
private EditText editnum;
private ExampleDialogListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Edit")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String editnumber=editnum.getText().toString();
listener.applynum(editnumber);
}
});
editnum = view.findViewById(R.id.editnum);
return builder.create();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener= (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()+ "must implement ExampleDialog Listener");
}
}
public interface ExampleDialogListener {
void applynum(String editnumber);
}
}
enter code here