という名前のレイアウト フォルダーに新しい .xml ファイルを作成しましたlog.xml
。含まれているのは 1 つだけTextView
です。
メイン アクティビティから log.xml にある textview にテキストを設定することは可能ですか? または、log.xml をビューとして使用するアクティビティでのみ設定できますか? ここで私が言いたいことを理解していただければ幸いです。
ありがとう
という名前のレイアウト フォルダーに新しい .xml ファイルを作成しましたlog.xml
。含まれているのは 1 つだけTextView
です。
メイン アクティビティから log.xml にある textview にテキストを設定することは可能ですか? または、log.xml をビューとして使用するアクティビティでのみ設定できますか? ここで私が言いたいことを理解していただければ幸いです。
ありがとう
「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.
以下の解決策は私のために働いた -
レイアウト XML ファイルの View オブジェクトを取得 (例: toast_loading_data) -
View layout = inflater.inflate(R.layout.toast_loading_data,
(ViewGroup) findViewById(R.id.toast_layout_root));
このビューから TextView 要素を取得します (例: TextView id - toast_text)-
TextView tvToast = (TextView) layout.findViewById(R.id.toast_text);
TextView のテキストを設定 -
tvToast.setText("Loading data for " + strDate + " ...");
以下は、メイン アクティビティからのカスタマイズされたトースト メッセージのスニペットです -
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
お役に立てれば
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);
}
}
私はあなたが言おうとしていることを理解していると思います。これを行う場合:
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText(output);
はtextView2
、テキストを設定するテキスト ビューの ID ですsetText()
。関数を使用して任意の文字列値に設定できます。お役に立てれば!