【问题标题】:change text color with spannable使用 spannable 更改文本颜色
【发布时间】:2021-12-30 23:51:41
【问题描述】:

在下面用于与 arduino 进行蓝牙消息传递的代码中,我试图更改一些静态字符串的颜色。 1.在开始按钮侦听器上,我有一条消息“连接已打开”,我正在使用 xml 文件更改颜色并在那里创建一个具有特定颜色的字符串。这种方法只在那里有效。 2. 我在发送按钮侦听器上尝试了另一种使用可扩展字符串的方法,但根本没有工作,消息是黑色的。 我想要做的是,当我在我的 textview 上发送消息时,我看到“发送数据:”+ 字符串(我发送的 msg),我希望这个发送数据是红色的,例如接收数据。 到现在为止我尝试的是代码。如果有任何想法可以尝试,我将不胜感激。

public class MainActivity extends Activity {
    
    private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
    private BluetoothDevice device;
    private BluetoothSocket socket;
    private OutputStream outputStream;
    private InputStream inputStream;
    Button startButton, sendButton,clearButton,stopButton;
    TextView textView;
    EditText editText;
    boolean deviceConnected=false;
    //Thread thread;
    byte[] buffer;
    //int bufferPosition;
    boolean stopThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startButton = findViewById(R.id.buttonStart);
        sendButton = findViewById(R.id.buttonSend);
        clearButton = findViewById(R.id.buttonClear);
        stopButton = findViewById(R.id.buttonStop);
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        textView.setMovementMethod(new ScrollingMovementMethod());
        setUiEnabled(false);

        startButton.setOnClickListener(v -> {

            if(BTinit())
            {
                if(BTconnect())
                {
                    setUiEnabled(true);
                    deviceConnected=true;
                    beginListenForData();
                    //textView.append("Connection Opened!");
                    String greenString = getResources().getString(R.string.Connection_Opened);
                    textView.append(Html.fromHtml(greenString));
                }

            }
        });
        sendButton.setOnClickListener(v -> {

            String t = "Send Data: ";
            SpannableString spannableString = new SpannableString(t);
            ForegroundColorSpan green = new ForegroundColorSpan(getResources().getColor(R.color.private_green));
            spannableString.setSpan(green, 0, 9, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

            String string = editText.getText().toString();
            String str = string.concat("\n");
            try {
                outputStream.write(str.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            textView.append(spannableString + str);
        });
        stopButton.setOnClickListener(v -> {
            try {
                stopThread = true;
                outputStream.close();
                inputStream.close();
                socket.close();
                setUiEnabled(false);
                deviceConnected=false;
                textView.append("Connection Closed!");
            }catch (IOException e){
                e.printStackTrace();
            }
        });
        clearButton.setOnClickListener(v -> textView.setText(""));
    }

    public void setUiEnabled(boolean bool)
    {
        startButton.setEnabled(!bool);
        sendButton.setEnabled(bool);
        stopButton.setEnabled(bool);
        textView.setEnabled(bool);

    }

    public boolean BTinit()
    {
        boolean found=false;
        BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
        }
        if(bluetoothAdapter !=null)
        {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);
        }
        assert bluetoothAdapter != null;
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if(bondedDevices.isEmpty())
        {
            Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
        }
        else
        {
            for (BluetoothDevice iterator : bondedDevices)
            {
                //private final String DEVICE_NAME="ArduinoBT";
                String DEVICE_ADDRESS = "98:DA:C0:00:2C:E2";
                if(iterator.getAddress().equals(DEVICE_ADDRESS))
                {
                    device=iterator;
                    found=true;
                    break;
                }
            }
        }
        return found;
    }

    public boolean BTconnect()
    {
        boolean connected=true;
        try {
            socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            connected=false;
        }
        if(connected)
        {
            try {
                outputStream=socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream=socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        return connected;
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        stopThread = false;
        buffer = new byte[1024];
        Thread thread  = new Thread(() -> {
            while(!Thread.currentThread().isInterrupted() && !stopThread)
            {
                try
                {
                    int byteCount = inputStream.available();
                    if(byteCount > 0)
                    {
                        byte[] rawBytes = new byte[byteCount];
                        inputStream.read(rawBytes);
                        final String string=new String(rawBytes, StandardCharsets.UTF_8);
                        handler.post(() -> textView.append("Receive data: " + string));

                    }
                }
                catch (IOException ex)
                {
                    stopThread = true;
                }
            }
        });

        thread.start();
    }
}

【问题讨论】:

标签: java android spannable


【解决方案1】:

这样试试;

Spannable text = new SpannableString("Send Data:");        

text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.private_green)), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多