安卓记事本添加打印功能

这段代码是一个Android应用程序中的一个活动(Activity)类,名为FileView。它继承自AppCompatActivity类,因此可以使用AndroidX库提供的样式和工具。

定义了几个成员变量:

fileHead:一个EditText控件,用于编辑文件标题。

fileBody:一个EditText控件,用于编辑文件内容。

fab_edit:一个FloatingActionButton按钮,用于触发编辑操作。

fileName:存储文件的名称。

stat:用于跟踪文件状态,初始值为0。

nitSettings:一个NitSettings对象,用于处理氮氧设置。
实现了onCreate()方法,在活动创建时被调用。在该方法中进行了以下操作:

调用nitSettings.loadNitState()方法加载氮氧设置,根据返回值设置主题(如果返回值为true,则使用DarkTheme主题;否则使用AppTheme主题)。

设置活动的标题为"Edit Jot"。

设置活动的布局文件为R.layout.activity_file_view。

初始化成员变量fileHead、fileBody和fab_edit。

从之前的意图(Intent)中获取传递的消息,并将其作为文件名存储在fileName变量中。

将文件名设置到fileHeadEditText控件中。

根据文件路径构建一个文件对象,然后读取文件内容到一个字符串变量readTxt中。
将字符串变量readTxt设置到fileBodyEditText控件中。
为fab_edit按钮设置了点击事件监听器,当点击该按钮时触发以下操作:

如果stat的值为0,将fileHead和fileBody设置为可获取焦点,并设置它们的焦点获取方式为"touch mode"。
否则,将fileHead和fileBody设置为不可获取焦点。

stat = 1;:将stat变量的值设为1。
fab_edit.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_black_24dp));:将fab_edit按钮的图像设置为一个保存图标。

Snackbar.make(v, getResources().getString(R.string.edit),

Snackbar.LENGTH_Short).show();:显示一个短暂的Snackbar,内容为编辑提示

String filename = fileHead.getText().toString();:获取fileHeadEditText控件中的文本内容,并将其转换为字符串。

String content = fileBody.getText().toString();:获取fileBodyEditText控件中的文本内容,并将其转换为字符串。
String folder_main = “MyJots”;:定义一个名为folder_main的字符串变量,并将其初始化为"MyJots"。

File f = new File(Environment.getExternalStorageDirectory() + “/” + folder_main);:创建一个文件对象f,路径为外部存储设备的"MyJots"文件夹。

if (!f.exists()) { f.mkdirs(); }:如果文件夹MyJots不存在,则创建该文件夹。

try { … } catch (Exception e) { … }:在try-catch块中写入文件内容到文件中。

fileBody.setFocusableInTouchMode(false);:将fileBodyEditText控件的焦点获取方式设置为不可用。

fileBody.clearFocus();:清除fileBodyEditText控件的焦点。

stat = 0;:将stat变量的值设为0。

fab_edit.setImageDrawable(getResources().getDrawable(R.drawable.ic_edit_black_24dp));:将fab_edit按钮的图像设置为一个编辑图标。

Snackbar.make(v, getResources().getString(R.string.Save),

Snackbar.Length_Short).show();:显示一个短暂的Snackbar,内容为保存提示。

AlertDialog alt_dia = new AlertDialog.Builder(FileView.this).create();:创建一个AlertDialog对象。

alt_dia.setTitle(R.string.Save);:设置AlertDialog的标题为保存提示。

alt_dia.setMessage(getResources().getString(R.string.back));:设置AlertDialog的消息为返回提示。

alt_dia.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { … });:为AlertDialog设置一个肯定按钮,并为其设置点击事件监听器。

alt_dia.setButton(AlertDialog.BUTTON_NEGATIVE,
getResources().getString(R.string.no), new DialogInterface.OnClickListener() { … });:为AlertDialog设置一个否定按钮,并为其设置点击事件监听器。
alt_dia.show();:显示AlertDialog。
java代码

package com.jotterpro.notes;import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;import android.os.Build;
import android.os.Bundle;import android.os.Environment;import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;import android.print.PrintJob;
import android.print.PrintManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.Toast;import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;import java.io.File;
import java.io.FileInputStream;import java.io.FileWriter;import java.io.InputStreamReader;import java.io.Reader;public class FileView extends AppCompatActivity {EditText fileHead, fileBody;FloatingActionButton fab_edit;String fileName;int stat = 0;NitSettings nitSettings;private static final int REQUEST_PERMISSION_CODE = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate( savedInstanceState );nitSettings = new NitSettings( this );setTitle( "Edit Jot" );if (nitSettings.loadNitState( ) == true) {setTheme( R.style.DarkTheme );} else {setTheme( R.style.AppTheme );}setContentView( R.layout.activity_file_view );fileHead = findViewById( R.id.edit_head );fileHead.setEnabled( false );fileBody = findViewById( R.id.edit_body );fileBody.setFocusableInTouchMode( false );fileBody.clearFocus( );fab_edit = findViewById( R.id.fab_edit );Intent intent = getIntent( );String pass = intent.getStringExtra( "message" );fileName = pass;fileHead.setText( pass );File f = new File( Environment.getExternalStorageDirectory( ) + "/" + "MyJots", pass );StringBuilder readTxt = new StringBuilder( );try {Reader reader = new InputStreamReader( new FileInputStream( f ) );char[] buff = new char[500];for (int charsRead; (charsRead = reader.read( buff )) != -1; ) {readTxt.append( buff, 0, charsRead );}} catch (Exception e) {Toast.makeText( getApplicationContext( ), e.getMessage( ), Toast.LENGTH_SHORT ).show( );}fileBody.setText( readTxt );fab_edit.setOnClickListener( new View.OnClickListener( ) {@Overridepublic void onClick(View v) {if (stat == 0) {fileHead.setFocusableInTouchMode( true );fileBody.setFocusableInTouchMode( true );stat = 1;fab_edit.setImageDrawable( getResources( ).getDrawable( R.drawable.ic_save_black_24dp ) );Snackbar.make( v, getResources( ).getString( R.string.edit ), Snackbar.LENGTH_SHORT ).show( );//Toast.makeText(getApplicationContext(),"Now you can edit your Jot",Toast.LENGTH_SHORT).show();} else {String filename = fileHead.getText( ).toString( );String content = fileBody.getText( ).toString( );String folder_main = "MyJots";File f = new File( Environment.getExternalStorageDirectory( ) + "/" + folder_main );if (!f.exists( )) {f.mkdirs( );}try {File nFile = new File( f + "/" + filename );FileWriter fw = new FileWriter( nFile );fw.write( content );fw.close( );} catch (Exception e) {Toast.makeText( getApplicationContext( ), e.getMessage( ), Toast.LENGTH_SHORT ).show( );}fileBody.setFocusableInTouchMode( false );fileBody.clearFocus( );stat = 0;fab_edit.setImageDrawable( getResources( ).getDrawable( R.drawable.ic_edit_black_24dp ) );Snackbar.make( v, getResources( ).getString( R.string.Save ), Snackbar.LENGTH_SHORT ).show( );//Toast.makeText(getApplicationContext(),"Jot Saved",Toast.LENGTH_SHORT).show();}}} );}@Overridepublic void onBackPressed() {AlertDialog alt_dia = new AlertDialog.Builder( FileView.this ).create( );alt_dia.setTitle( R.string.Save );alt_dia.setMessage( getResources( ).getString( R.string.back ) );alt_dia.setButton( AlertDialog.BUTTON_POSITIVE, getResources( ).getString( R.string.Yes ), new DialogInterface.OnClickListener( ) {@Overridepublic void onClick(DialogInterface dialog, int which) {HomeActivity( );}} );alt_dia.setButton( AlertDialog.BUTTON_NEGATIVE, getResources( ).getString( R.string.No ), new DialogInterface.OnClickListener( ) {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.cancel( );}} );alt_dia.show( );}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater( );inflater.inflate( R.menu.delete_menu, menu );return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {int del_menu_id = item.getItemId( );switch (del_menu_id) {case R.id.opt_del:AlertDialog alt = new AlertDialog.Builder( FileView.this ).create( );alt.setTitle( R.string.Warning );alt.setMessage( getResources( ).getString( R.string.delete ) + fileName + "?" );alt.setButton( AlertDialog.BUTTON_POSITIVE, getResources( ).getString( R.string.Yes ), new DialogInterface.OnClickListener( ) {@Overridepublic void onClick(DialogInterface dialog, int which) {File f = new File( Environment.getExternalStorageDirectory( ) + "/MyJots" + "/" + fileName );f.delete( );finish( );HomeActivity( );Toast.makeText( getApplicationContext( ), getResources( ).getString( R.string.File_Deleted ), Toast.LENGTH_SHORT ).show( );}} );alt.setButton( AlertDialog.BUTTON_NEGATIVE, getResources( ).getString( R.string.No ), new DialogInterface.OnClickListener( ) {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.cancel( );}} );alt.show( );return true;default:return super.onOptionsItemSelected( item );case R.id.opt_share:Intent intent = new Intent( Intent.ACTION_SEND );intent.setType( "text/plain" );intent.putExtra( Intent.EXTRA_TEXT, fileBody.getText( ).toString( ) );startActivity( Intent.createChooser( intent, "分享到" ) );return true;case R.id.opt_print:printNotes();return true;}}public void HomeActivity() {Intent HomeIntent = new Intent(this, HomeScreen.class);if (nitSettings.loadNitState() == true) {HomeIntent.putExtra("nitVal", "One");} elseHomeIntent.putExtra("nitVal", "Zero");startActivity(HomeIntent);overridePendingTransition(R.anim.left_enter, R.anim.right_out);}private void printNotes() {if (fileName.isEmpty()) {Toast.makeText(this, "没有任何笔记可以打印", Toast.LENGTH_SHORT).show();} else {StringBuilder sb = new StringBuilder();sb.append("标题: ").append(fileHead.getText( ).toString( )).append("\n");sb.append("内容: ").append(fileBody.getText( ).toString( )).append("\n\n");// 创建一个 WebView,并加载要打印的内容WebView webView = new WebView(this);webView.loadDataWithBaseURL(null, sb.toString(), "text/plain", "UTF-8", null);// 获取 PrintManager 实例PrintManager printManager = null;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);}// 设置打印任务名称和打印文档适配器String jobName = getString(R.string.app_name) + " 打印任务";PrintDocumentAdapter printAdapter = null;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {printAdapter = webView.createPrintDocumentAdapter(jobName);}// 开始打印PrintJob printJob = null;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {printJob = printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());}if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {if (printJob.isCompleted()) {Toast.makeText(this, "打印完成", Toast.LENGTH_SHORT).show();} else if (printJob.isFailed()) {Toast.makeText(this, "打印失败", Toast.LENGTH_SHORT).show();}}}}}

在AndroidManifest.xml添加



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部