2017-06-15 3 views
0

私はtextViewsを持っていますactivityを持っていますが、textViewsにはsetText()メソッドが適用されています。ここでの問題は、最初textView2131099682 textと第二を示していることアンドロイドのsetText()にはゴミ値が表示されます

public class MainActivity extends AppCompatActivity { 

    TextView text1,text2; 


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

     text1=(TextView)findViewById(R.id.text1); 
     text2=(TextView)findViewById(R.id.text2); 

     text1.setText(R.string.display+" text"); 
     text2.setText("Display"+" text"); 
    } 

} 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<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="com.example.shaloin.settext.MainActivity"> 


    <TextView 
     android:id="@+id/text1" 
     android:layout_marginTop="30dp" 

     android:layout_width="match_parent" 
     android:textSize="20sp" 
     android:layout_height="wrap_content" 
     android:textColor="#000000"/> 
    <TextView 
     android:id="@+id/text2" 
     android:layout_marginTop="30dp" 
     android:layout_below="@+id/text1" 
     android:layout_width="match_parent" 
     android:textSize="20sp" 
     android:layout_height="wrap_content" 
     android:textColor="#000000"/> 

</RelativeLayout> 

のstrings.xml

<string name="display">Display : </string> 

:コードを以下に示します。 textViewDisplay textを示します。なぜこれが起こっているのか理解できません。

また、text1.setText(R.string.display+" text");text1.setText(R.string.display);に変更すると、通常の出力はDisplayになります。誰も私の疑いを明確にしてください。出力を示す画像を添付しました。ありがとう:)

Screen

答えて

1

R.string.displayが実際の数値IDで、これはあなたが見ているものです。代わりに使用する必要があるのはgetString(R.string.display)

IDだけを使用することにより、setTextは整数を渡して文字列自体を解決することがわかります。しかし、後ろに文字列を追加すると、setTextはそれを文字列とみなして、それを取得したときと同じように出力します。

+0

なぜ 'text1.setText(R.string.display);'はガベージ値を表示しませんか? –

+0

これは、setTextメソッドがIDまたは文字列のいずれかを取るためです。 IDだけを渡すと、その文字列が検索されます。あなたがしていたのは 'R.string.display +" text "'だったので、関数に1232123を渡すのではなく、文字列である "1232123 text"を渡し、関数はそのまま文字列を出力します。 – Aenadon

+0

説明ありがとうございました:) –

0

あなたはアプリのコンテキストを取得する必要があります。

textViewID.setText(context.getResources()はgetString(R.string.display + "他に何かしたい場合は");。

私はint型に取るメソッドを作成したいし、私が作りますtextViewID.setText(R.id.display)+ "必要ならば何か他のもの");

textViewID.setText(R.string.display)が機能しない理由は実際にはint値(R.string.display)を使用すると、そのリソースの値を取得する必要があります。

+0

説明ありがとうございました:) –

0

リソースから文字列値をアクティビティに直接取得することはできません。リソースオブジェクトでそれらを取得する必要があります。現在、あなたはこのように値を取得している:

text1.setText(R.string.display+" text"); 

変更、それに:コーディング

text1.setText(getResources().getString(R.string.display) + " text"); 

ハッピー!

+0

説明ありがとうございました:) –

+0

よろしくお願いします! –

関連する問題