setText无法翻译,如何将电池信息字串正确显示

时间:2016-05-17 04:54:22

标签: android string settext battery

嗨我正在尝试将batteryinfo.setText串起来,我不知道该怎么做。它的工作但信息显示不准确。帮我正确串起来。

  public class Main extends Activity implements SensorEventListener {

            private TextView batteryInfo;



            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                PackageManager pm = getPackageManager();
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

                batteryInfo=(TextView)findViewById(R.id.battinfo);

        his.registerReceiver(this.batteryInfoReceiver,  new IntentFilter(Intent.ACTION_BATTERY_CHANGED));


         private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    int  level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
                    int  temperature= intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);
                    int  voltage= intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);


               //issues fixed for setText can not be translated 



batteryInfo.setText(String.format(getString(R.string.battery_display),level,temperature,voltage));
                    }
                };

            }

XML

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/battinfo"
        android:id="@+id/battinfo"
        android:textColor="@android:color/holo_blue_dark"
        android:layout_below="@+id/imageViewCompass"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />

字符串

//添加了电池显示字符串

<string name="battinfo">Battery Status</string>
<string name="battery_display">BATT:  %1$d \n HEAT: %2$d °C\n  VOLT: %3$d \n</string>

2 个答案:

答案 0 :(得分:0)

试试这个

batteryInfo.setText ("BATT:  "+String.valueOf(level)+"%\n"+  "HEAT: "+String.valueOf(temperature)+"°C\n"+  "VOLT: "+String.valueOf(voltage)+"mV\n");

它会将这些变量从整数转换为字符串,因为textviews只接受字符串。

确定在Strings.xml上创建这样的东西

<string name="battery_display">BATT:  %1$d \n HEAT: %2$d °C\n  VOLT: %3$d \n</string>

以及您的活动

batteryInfo.setText(String.format(getString(R.string.battery_display),level,temperature,voltage));

答案 1 :(得分:0)

将您要设置的文字放在TextView中的strings.xml

你的字符串将是:

<string name="battery_text" formatted="false">BATT:%d%% \n HEAT: %d &#8451; \n VOLT: %dmV</string>

在onReceive()中从strings.xml中获取字符串

batteryInfo.setText.(String.format(context.getString(R.string.battery_text),level,temperature,voltage));