5

という名前のレイアウト フォルダーに新しい .xml ファイルを作成しましたlog.xml。含まれているのは 1 つだけTextViewです。

メイン アクティビティから log.xml にある textview にテキストを設定することは可能ですか? または、log.xml をビューとして使用するアクティビティでのみ設定できますか? ここで私が言いたいことを理解していただければ幸いです。

ありがとう

4

4 に答える 4

11

「setContentView()」で話しているxmlを設定しない場合は、いつでもレイアウトインフレータで取得できます。ただし、 addView() を使用して現在のレイアウトにテレビを追加する必要があります。

LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View vi = inflater.inflate(R.layout.log, null); //log.xml is your file.
TextView tv = (TextView)vi.findViewById(R.id.tv); //get a reference to the textview on the log.xml file. 
于 2012-06-23T23:40:52.363 に答える
0

以下の解決策は私のために働いた -

  1. レイアウト XML ファイルの View オブジェクトを取得 (例: toast_loading_data) -

    View layout = inflater.inflate(R.layout.toast_loading_data,
            (ViewGroup) findViewById(R.id.toast_layout_root));
    
  2. このビューから TextView 要素を取得します (例: TextView id - toast_text)-

    TextView tvToast = (TextView) layout.findViewById(R.id.toast_text);
    
  3. TextView のテキストを設定 -

    tvToast.setText("Loading data for " + strDate + " ...");
    
  4. 以下は、メイン アクティビティからのカスタマイズされたトースト メッセージのスニペットです -

    View layout = inflater.inflate(R.layout.toast_loading_data,
            (ViewGroup) findViewById(R.id.toast_layout_root));
    TextView tvToast = (TextView) layout.findViewById(R.id.toast_text);
    tvToast.setText("Loading data for " + strDate + " ...");
    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER, 0, 0); //Set toast gravity to bottom
    toast.setDuration(Toast.LENGTH_LONG);   //Set toast duration
    toast.setView(layout);  //Set the custom layout to Toast
    

お役に立てれば

于 2015-03-23T10:30:31.593 に答える
0

log.xml が現在の可視レイアウトに含まれていない限り、findViewById() は null を返します。

新しいアクティビティにロードするときに TextView のテキストを設定したいので、アクティビティの開始に使用されるインテントに新しい文字列を渡すことができます。

最初のアクティビティの適切な onClick() で:

Intent intent = new Intent(this, Second.class);
intent.putExtra("myTextViewString", textString);
startActivity(intent);

2 番目のアクティビティの onCreate() で:

setContentView(R.layout.log);

TextView textView = (TextView) findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if(extras != null) {
    String newText = extras.getString("myTextViewString");
    if(newText != null) {
        textView.setText(newText);
    }
}
于 2012-06-24T00:03:03.577 に答える
-1

私はあなたが言おうとしていることを理解していると思います。これを行う場合:

TextView tv = (TextView) findViewById(R.id.textView2);    
tv.setText(output);

textView2、テキストを設定するテキスト ビューの ID ですsetText()。関数を使用して任意の文字列値に設定できます。お役に立てれば!

于 2012-06-23T23:41:28.167 に答える