我在我的佈局文件夾中創建了一個名爲log.xml
的新.xml文件。它只包含一個TextView
。從主活動更新不同佈局xml中的textview
是否有可能從我的主要活動設置位於log.xml文本視圖的文本?或者只能在使用log.xml作爲視圖的活動中進行設置?希望你明白我在這裏的意思,否則就不好說了。
感謝
我在我的佈局文件夾中創建了一個名爲log.xml
的新.xml文件。它只包含一個TextView
。從主活動更新不同佈局xml中的textview
是否有可能從我的主要活動設置位於log.xml文本視圖的文本?或者只能在使用log.xml作爲視圖的活動中進行設置?希望你明白我在這裏的意思,否則就不好說了。
感謝
如果不設置你在談論的XML「的setContentView()」你總是可以佈局吹氣得到它。您必須使用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.
我會試試看,謝謝 – Johan
正是我在找的。謝謝。 –
嗨Nuno,上面的膨脹工作正常。我想在特定位置更新textview值。任何幫助。?因爲,在內部佈局中,我有按鈕,當點擊按鈕時,它從服務器獲得響應,並顯示特定文本視圖中的更新 – harikrishnan
我想我明白你在說什麼。如果你這樣做:
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText(output);
其中textView2
是你要設置的文字文本視圖的ID,您可以在使用setText()
功能設置爲任何字符串值。希望這可以幫助!
除非log.xml包含在當前的可見佈局中,findViewById()將返回null。
由於您希望在將新文本加載到新活動時設置TextView文本,因此可以在用於啓動活動的Intent中傳遞新字符串。
在適當的onClick()從您的第一項活動:
Intent intent = new Intent(this, Second.class);
intent.putExtra("myTextViewString", textString);
startActivity(intent);
在你的第二個活動的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);
}
}
以下解決方案爲我 -
獲取佈局XML文件的視圖對象(例如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
希望這有助於您的
您的mainActivity有一個名爲main.xml的主佈局,並且您添加了一個新的佈局log.xml,所以您應該創建一個新的Activity,並且您可以通過使用intent從第一個Activity(MainActivity) – Houcine
你打算什麼時候顯示log.xml;在新的Activity中,作爲ListView(或Spinner等)中的一行,作爲當前Activity中的新視圖? – Sam
@Sam作爲一個新的活動,當點擊我的main.xml中的一個按鈕。 – Johan