从主活动更新不同布局xml中的textview

时间:2012-06-23 23:33:32

标签: android

我在我的布局文件夹中创建了一个名为log.xml的新.xml文件。它只包含一个TextView

是否可以在我的主要活动中设置位于log.xml中的textview上的文本?或者只能在使用log.xml作为视图的活动中设置它?希望你能明白我的意思,否则就会很复杂。

由于

4 个答案:

答案 0 :(得分:11)

如果你没有在" setContentView()"上设置你正在谈论的xml。你可以随时通过布局inflater获得它。您必须使用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. 

答案 1 :(得分:0)

除非当前包含log.xml,否则可见布局findViewById()将返回null。

由于您想在新活动中加载TextView的文本时,可以在用于启动活动的Intent中传递新的String。

来自第一个活动的相应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);
    }
}

答案 2 :(得分: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. 以下是来自主要活动的自定义Toast消息的片段 -

    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
    
  5. 希望这有帮助

答案 3 :(得分:-1)

我想我明白你想说的话。如果你这样做:

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

其中textView2是您要设置文本的文本视图的ID,您可以使用setText()函数将其设置为任何字符串值。希望这有帮助!