Я новичок в Java и XML и после просмотра нескольких руководств начал создавать собственное приложение-календарь. В этом приложении есть фрагмент календаря, содержащий TextView, который показывает «С возвращением @USERNAME».
Я создал действие, которое открывается при первом запуске и запрашивает имя пользователя, и который хранит имя в классе GlobalVariable как «String first_name».
Но когда я запускаю приложение, после указания имени оно не меняется в тексте приветствия. Я проверил, не возникла ли проблема в моей глобальной переменной, заменив в setText() случайную строку, и она все еще не работает.
Не могли бы вы мне помочь, пожалуйста?
CalendarFragment.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class CalendarFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
TextView welcomeMessage = (TextView) view.findViewById(R.id.welcomeBackTitle);
welcomeMessage.setText(GlobalVariable.first_name);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
}
fragment_calendar.xml
MainActivity.java
import android.app.Dialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.airbnb.lottie.LottieAnimationView;
import com.example.tasklins.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
//Alert Dialog for the new calendar creation
Dialog dialog;
Button btnDialogCancel, btnDialogYes;
TextView titleDialog, subTitleDialog;
// Keep the ID of the current page, on calendar by default
int currentPage = R.id.calendar, newPage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//multiple windows binding
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
fragmentSelection(currentPage);
binding.bottomNavigationView.setBackground(null);
//initialisation of dialog box and buttons
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_box_new_calendar);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.new_calendar_dialog_bg));
dialog.setCancelable(false); //impossible to quit the dialog without clicking yes or no
titleDialog = dialog.findViewById(R.id.title);
subTitleDialog = dialog.findViewById(R.id.alertInformation);
btnDialogYes = dialog.findViewById(R.id.btnDialogYes);
btnDialogCancel = dialog.findViewById(R.id.btnDialogCancel);
btnDialogCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btnDialogYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPage = newPage;
fragmentSelection(currentPage);
dialog.dismiss();
}
});
binding.bottomNavigationView.setOnItemSelectedListener(item-> {
//TODO : ADD A CLEAR PAGE FEATURE FOR THE CALENDAR
newPage = item.getItemId();
if(currentPage == R.id.addCalendar)
{
newDialog("Are you sure ?", "You are about to leave the add calendar page. You will lose all your modifications. Do you really want to leave?", "Yes", "Stay Here");
dialog.show();
}
else {
currentPage = newPage;
fragmentSelection(item.getItemId());
}
return true;
});
binding.addCalendar.setBackground(null);
binding.addCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newDialog("Confirm Changement ?", "Are you sure you want to create a new calendar? Your weekly progress will be deleted.", "Yes", "Cancel");
newPage = R.id.addCalendar;
dialog.show();
}
});
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransaction.replace(R.id.frame_layout, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
}
public void fragmentSelection(int destinationID)
{
if(destinationID == R.id.calendar) {
replaceFragment(new CalendarFragment());
} else if (destinationID == R.id.progress) {
replaceFragment(new ProgressFragment());
} else if (destinationID == R.id.addCalendar) {
replaceFragment(new NewCalendarFragment());
} else if (destinationID == R.id.tasklin) {
replaceFragment(new TasklinFragment());
} else {
replaceFragment(new ProfileFragment());
}
}
// Method that helps creating dynamic dialogs
public void newDialog(String title, String content, String btnYes, String btnNo) {
titleDialog.setText(title);
subTitleDialog.setText(content);
btnDialogYes.setText(btnYes);
btnDialogCancel.setText(btnNo);
}
}````
Подробнее здесь: https://stackoverflow.com/questions/781 ... s-textview
Невозможно изменить TextView фрагмента. ⇐ JAVA
Программисты JAVA общаются здесь
1710714896
Anonymous
Я новичок в Java и XML и после просмотра нескольких руководств начал создавать собственное приложение-календарь. В этом приложении есть фрагмент календаря, содержащий TextView, который показывает «С возвращением @USERNAME».
Я создал действие, которое открывается при первом запуске и запрашивает имя пользователя, и который хранит имя в классе GlobalVariable как «String first_name».
Но когда я запускаю приложение, после указания имени оно не меняется в тексте приветствия. Я проверил, не возникла ли проблема в моей глобальной переменной, заменив в setText() случайную строку, и она все еще не работает.
Не могли бы вы мне помочь, пожалуйста?
CalendarFragment.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class CalendarFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
TextView welcomeMessage = (TextView) view.findViewById(R.id.welcomeBackTitle);
welcomeMessage.setText(GlobalVariable.first_name);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
}
fragment_calendar.xml
MainActivity.java
import android.app.Dialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.airbnb.lottie.LottieAnimationView;
import com.example.tasklins.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
//Alert Dialog for the new calendar creation
Dialog dialog;
Button btnDialogCancel, btnDialogYes;
TextView titleDialog, subTitleDialog;
// Keep the ID of the current page, on calendar by default
int currentPage = R.id.calendar, newPage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//multiple windows binding
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
fragmentSelection(currentPage);
binding.bottomNavigationView.setBackground(null);
//initialisation of dialog box and buttons
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_box_new_calendar);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.new_calendar_dialog_bg));
dialog.setCancelable(false); //impossible to quit the dialog without clicking yes or no
titleDialog = dialog.findViewById(R.id.title);
subTitleDialog = dialog.findViewById(R.id.alertInformation);
btnDialogYes = dialog.findViewById(R.id.btnDialogYes);
btnDialogCancel = dialog.findViewById(R.id.btnDialogCancel);
btnDialogCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btnDialogYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPage = newPage;
fragmentSelection(currentPage);
dialog.dismiss();
}
});
binding.bottomNavigationView.setOnItemSelectedListener(item-> {
//TODO : ADD A CLEAR PAGE FEATURE FOR THE CALENDAR
newPage = item.getItemId();
if(currentPage == R.id.addCalendar)
{
newDialog("Are you sure ?", "You are about to leave the add calendar page. You will lose all your modifications. Do you really want to leave?", "Yes", "Stay Here");
dialog.show();
}
else {
currentPage = newPage;
fragmentSelection(item.getItemId());
}
return true;
});
binding.addCalendar.setBackground(null);
binding.addCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newDialog("Confirm Changement ?", "Are you sure you want to create a new calendar? Your weekly progress will be deleted.", "Yes", "Cancel");
newPage = R.id.addCalendar;
dialog.show();
}
});
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransaction.replace(R.id.frame_layout, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
}
public void fragmentSelection(int destinationID)
{
if(destinationID == R.id.calendar) {
replaceFragment(new CalendarFragment());
} else if (destinationID == R.id.progress) {
replaceFragment(new ProgressFragment());
} else if (destinationID == R.id.addCalendar) {
replaceFragment(new NewCalendarFragment());
} else if (destinationID == R.id.tasklin) {
replaceFragment(new TasklinFragment());
} else {
replaceFragment(new ProfileFragment());
}
}
// Method that helps creating dynamic dialogs
public void newDialog(String title, String content, String btnYes, String btnNo) {
titleDialog.setText(title);
subTitleDialog.setText(content);
btnDialogYes.setText(btnYes);
btnDialogCancel.setText(btnNo);
}
}````
Подробнее здесь: [url]https://stackoverflow.com/questions/78177161/impossible-to-change-a-fragments-textview[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия