Android中的回调

问题描述 投票:1回答:1

我是Android和整个编程领域的新手,我在回调方面需要一点帮助。我了解回调的要点,但不确定如何实现。

上下文:我正在编写一个简单的笔记应用程序,该应用程序允许用户编写文本并将其保存到该应用程序中。然后,用户可以使用按钮请求读取文件。然后,文本将显示在主活动的textview上。有一个选项可以擦除此文件,这是通过弹出确认窗口完成的,这是另一项活动。此弹出窗口包含2个按钮,其中一个取消和一个擦除。如果文件不为空,它将擦除,如果为空,则不执行任何操作。我不确定这是否是实现它的最佳方法,但我想使用“擦除”按钮回调到主活动以清除textview。我想到的方法是使用回调将布尔值发送回。主要活动将检查布尔值是否为true并清除textview(如果是)。我不确定如何在弹出窗口中实现回调以将该布尔值发送回主要活动。

主要活动代码

public class MainActivity extends AppCompatActivity implements Popout.ClearTextView {

    Button bnRead,bnWrite,bnClear;
    TextView tvFileOP;
    EditText etInput;
    //    private static final String INPUT_CONTENT = "inputContent";
    public static final String  TV_CONTENT = "textViewContent";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bnRead = (Button) findViewById(R.id.bnRead);
        bnWrite = (Button) findViewById(R.id.bnWrite);
        bnClear = (Button) findViewById(R.id.bnClear);

        tvFileOP = (TextView) findViewById(R.id.tvFileOP);
        etInput = (EditText) findViewById(R.id.etInput);
        tvFileOP.setMovementMethod(new ScrollingMovementMethod());

        final String fileName = "test_file";
        String data;

        bnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    FileInputStream fIn = openFileInput(fileName);
                    int c;
                    String temp = "";
                    while ( (c=fIn.read()) != -1){
                        temp = temp + Character.toString((char) c);
                    }
                    tvFileOP.setText(temp);
                    Toast.makeText(getBaseContext(),"file successfully read", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        bnWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data = etInput.getText().toString();
                try {
                    FileOutputStream fOut = openFileOutput(fileName,MODE_APPEND);
                    fOut.write(data.getBytes());
                    fOut.close();
                    etInput.setText("");
                    Toast.makeText(getBaseContext(),"file successfully written", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        bnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,Popout.class));
            }
        });

    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putString(TV_CONTENT,tvFileOP.getText().toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        tvFileOP.setText(savedInstanceState.getString(TV_CONTENT));
    }


    @Override
    public void clearTextView(Boolean clear) {
        if (clear){
            tvFileOP.setText("");
        }
    }
}

弹出确认菜单的代码

public class Popout extends AppCompatActivity {

    Button bnClosepopup,bnWipe;
    TextView tvConfirmation;
    String fileName = "test_file";
    TextView tvFileOP;

    public interface ClearTextView {
        public void clearTextView(Boolean clear);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popupwindow);

        bnClosepopup = (Button) findViewById(R.id.bnClosepopup);
        bnWipe = (Button) findViewById(R.id.bnWipe);
        tvConfirmation = (TextView) findViewById(R.id.tvConfirmation);


        //HIDING THE TOOL BAR AT THE TOP OF THE SCREEN
        this.getSupportActionBar().hide();

        //GETTING THE SIZE OF THE SCREEN
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;
        getWindow().setLayout((int) (width*0.8) , (int) (0.8*height));

        bnClosepopup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        bnWipe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File dir = getFilesDir();
                    File file = new File(dir, fileName);
                    boolean deleted = file.delete();
                    Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();

                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                }
                finish();

            }
        });
    }
}

我对android开发非常陌生,关于如何改进我的代码的任何提示将不胜感激:)

android callback
1个回答
0
投票

在这种情况下,无法将接口传递给其他活动,因为这是活动与活动的通信。

您必须使用其他方法,有多种方法,我能想到的最好方法是使用startActivityForResult()启动活动,然后等待响应返回,然后在通过覆盖MainActivity方法的onActivityResult()

示例

MainActivity

    //on click of this button
    bnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this,Popout.class);
            int requestCode = 12; //it could be whatever you want
            startActivityForResult(intent , requestCode);

        }
    });


//override this method


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

//this is triggered when you finish the Popout Activity
if(requestCode == 12 && resultCode == Activity.RESULT_OK){

// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false); //false is default if no value exists

}


}

Popout活动中:

    bnWipe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                File dir = getFilesDir();
                File file = new File(dir, fileName);
                boolean deleted = file.delete();

                //send the result to onActivtyResult() in MainActivity
                Intent result = new Intent();
                result.putExtra("deleted_state", deleted ); 
                setResult(Activity.RESULT_OK, result);

                Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();

            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
            finish();

        }
    });
© www.soinside.com 2019 - 2024. All rights reserved.