2016-10-04 100 views
2

我正在使用包含content_main.xml布局的Android Studio标准模板“导航抽屉活动”。在MainActivity.java的content_main.xml中更改TextView

在这个布局是我的textView,我想改变我的MainActivity.java文本。

我尝试以下,但没有任何变化:

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE); 
      View view = inflater.inflate(R.layout.content_main, null); 
      TextView txt = (TextView)view.findViewById(R.id.txt_head); 
      txt.setText("sdfsdf"); 

content_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 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:id="@+id/relativelayout_for_fragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.w4ter.ledcontroldesign.MainActivity" 
    tools:showIn="@layout/app_bar_main" 
    android:orientation="vertical" 
    android:paddingTop="10dp"> 

    <TextView 
     android:text="Presets" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textAppearance="@style/TextAppearance.AppCompat.Headline" 
     android:id="@+id/txt_head" /> 

    <View 
     android:layout_width="fill_parent" 
     android:layout_height="1dip" 
     android:background="#61000000" /> 
</LinearLayout> 

回答

1

没有必要LayoutInflater的。简单地使用:

TextView textView = (TextView) findViewById(R.id.txt_head); 
texView.setText("Hello"); 

希望这会有所帮助。

+0

哇我太瞎了O.o谢谢! – Waterfront

+0

No Worries .. :) – Harv

0

您只需以正常方式访问TextView组件。与模板content_main.xml包括主要布局在里面,所以你做前人的精力在你的主要活动如下(也许是onCreate方法或任何你内心的需要):

public class MainActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener { 

    //... 

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

     TextView txt = (TextView)view.findViewById(R.id.txt_head); 
     txt.setText("sdfsdf"); 
    } 

    //... 
} 

假设你有一个app_bar_main。主布局内的xml包含content_main.xml。最后,由于布局包含在主布局中,因此可以直接从主要活动访问所有内容。

希望它有帮助!

+0

谢谢你,我太盲目了......! – Waterfront