Je viens de commencer à apprendre Android
et j'ai un problème. Avec le nouveau Android Studio
j'ai deux fichiers XML
pour chaque activité, afin de ne pas obtenir NullPointerException
J'ai dû changer un peu ma findViewById. Mais maintenant je suis incapable de changer le texte en TextView
.Android - Impossible de changer le texte dans TextView
Code:
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);
}
}
fichiers 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" />
setContentView() lit automatiquement tous vos points de vue qui sont à l'intérieur existaient à l'écran d'activité. Pas besoin de gonfler la mise en page. –
s'il vous plaît mettre à jour votre code XML complet activity_main.xml – Pavan
Bonjour s'il vous plaît vérifier ma réponse mise à jour, vous aurez surmonté de votre problème :) –