2016-10-04 9 views
2

私はAndroid Studioの標準テンプレート "navigation drawer Activity"を使用しています。これにはcontent_main.xmlレイアウトが含まれています。MainActivity.javaのcontent_main.xmlの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

いいえ心配.. :) – Harv

0

通常の方法でTextViewコンポーネントにアクセスすればよいだけです。 (多分のonCreateメソッドまたはどこでも必要な内部の)あなたの主な活動で次のようにあなたがsouldのでcontent_main.xmlは、メインレイアウトの内側に含まれているテンプレートを使用して:

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を持っていると仮定すると。 content_main.xmlを含むメインレイアウト内のxml。最終的には、レイアウトはメインレイアウトに含まれているため、すべてのアクティビティから直接アクセスできます。

希望すると助かります!

+0

ありがとう、私はとても盲目だった...! – Waterfront

関連する問題