2015-12-04 1 views
2

Я только начал учиться Android, и у меня есть проблема. С новым Android Studio у меня есть два файла XML для каждого вида деятельности, поэтому не получить NullPointerException Мне пришлось немного изменить свой findViewById. Но теперь я не могу изменить текст в TextView.Android - Невозможно изменить текст в TextView

Код:

public class MainActivity extends AppCompatActivity { 


    LinearLayout layoutMain; 
    TextView tvText; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     layoutMain = (LinearLayout) View.inflate(this, R.layout.content_main, null); 
     tvText = (TextView) layoutMain.findViewById(R.id.tvText); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     int id = item.getItemId(); 

     switch (id) { 
      case R.id.action_settings1: 
        tvText.setText("one"); 
       Log.d("USER","one"); 
       break; 
      case R.id.action_settings2: 
       tvText.setText("two"); 
       Log.d("USER", "two"); 
       break; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

} 

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:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.myapp6.MainActivity" 
    tools:showIn="@layout/activity_main"> 


    <TextView 
     android:id="@+id/tvText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hello World!" /> 
</LinearLayout> 

<android.support.design.widget.AppBarLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:theme="@style/AppTheme.AppBarOverlay"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" 
     app:popupTheme="@style/AppTheme.PopupOverlay" /> 

</android.support.design.widget.AppBarLayout> 

<include layout="@layout/content_main" /> 

+0

setContentView() будет автоматически считывать все ваши мнения, которые существовали в пределах экрана деятельности. Не нужно раздувать макет. –

+0

обновите свой полный xml-код activity_main.xml – Pavan

+0

Здравствуйте, пожалуйста, проверьте мой обновленный ответ, который вы обязательно преодолеете из своей проблемы :) –

ответ

2

Изменить

tvText = (TextView) layoutMain.findViewById(R.id.tvText); 

в

tvText = (TextView) findViewById(R.id.tvText); 

Вы были получать неверную ссылку на TextView.

+0

Спасибо! Я изменил его, потому что раньше я получил исключение nullPointerException, но теперь кажется, что все в порядке. – iluvatar

+0

Добро пожаловать :) Эти макеты могут быть немного сложными .. –

2
public class MainActivity extends AppCompatActivity { 

View includedView; 
TextView tvText; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    includedView = (View) findViewById(R.id.includedView); 
    tvText = (TextView) includedView.findViewById(R.id.tvText); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 

    switch (id) { 
     case R.id.action_settings1: 
       tvText.setText("one"); 
      Log.d("USER","one"); 
      break; 
     case R.id.action_settings2: 
      tvText.setText("two"); 
      Log.d("USER", "two"); 
      break; 
    } 
    return super.onOptionsItemSelected(item); 
} 

} 

Также немного изменить бит в ваших 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:layout_width="match_parent" 
android:layout_height="match_parent" 
app:layout_behavior="@string/appbar_scrolling_view_behavior" 
tools:context="com.example.myapp6.MainActivity" 
tools:showIn="@layout/activity_main"> 


<TextView 
    android:id="@+id/tvText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" /> 
</LinearLayout> 

и второй XML

<android.support.design.widget.AppBarLayout 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:theme="@style/AppTheme.AppBarOverlay"> 

<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:layout_width="match_parent" 
    android:layout_height="?attr/actionBarSize" 
    android:background="?attr/colorPrimary" 
    app:popupTheme="@style/AppTheme.PopupOverlay" /> 

</android.support.design.widget.AppBarLayout> 

<include layout="@layout/content_main" 
android:id="@+id/includedView"/> 
0

Скопируйте и вставьте ваш content_main расположение внутри activity_main XML и удалить файл content_main XML.

Затем измените код в onCreate() как:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     layoutMain = (LinearLayout) findViewById(R.id.content_main); 
     //content_main should be the id of the layout you copied! 

     tvText = (TextView) findViewById(R.id.tvText); 
    } 

 Смежные вопросы

  • Нет связанных вопросов^_^