2013-12-23 2 views
0

В моем приложении adnroid, когда пользователь переходит в свой профиль, есть фрагмент с двумя кнопками - X точек и настроек. Для кнопок X пунктов я хочу изменить текст на любое количество очков, которое у них есть, например 12 очков.Как изменить текст внутри фрагмента из активности?

Я пробовал множество вещей, но ничего, кажется, работает:

Попытка 1:

 myProfileActionButtonsHolder = (TableRow) findViewById(R.id.myProfileActionButtonsHolder); 
     getSupportFragmentManager().beginTransaction().replace(R.id.myProfileActionButtonsHolder, new MyProfileActionButtonsFragment()).commit(); 

     MyProfileActionButtonsFragment.bMyProfilePoints = (Button) findViewById(R.id.bMyProfilePoints); 
     MyProfileActionButtonsFragment.bMyProfilePoints.setText("asd"); 

Попытка 2:

MyProfileActionButtonsFragment myProfileActionButtonsFragment = (MyProfileActionButtonsFragment) getSupportFragmentManager().findFragmentById(R.id.myProfileActionButtonsHolder); 
    ((Button)myProfileActionButtonsFragment.getView().findViewById(R.id.bMyProfileSettings)).setText("asd"); 

Попытка 3

myProfileActionButtonsFragment.setBMyProfileSettingsText("asd"); //setBMyProfileSettingsText is a custom method defined inside the fragment 

Здесь как мой фрагмент l ooks:

public class MyProfileActionButtonsFragment extends SherlockFragment { 
    public static Button bMyProfilePoints; 
    public Button bMyProfileSettings; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

     View view= inflater.inflate(R.layout.my_profile_action_buttons_fragment, container, false); 
     bMyProfilePoints = (Button) view.findViewById(R.id.bMyProfilePoints); 
     bMyProfileSettings = (Button) view.findViewById(R.id.bMyProfileSettings); 

     return view; 
    } 

    public void setBMyProfileSettingsText(String text) { 
     bMyProfilePoints.setText(text); 
    } 
} 

Im ВСЕГДА получаю NullPointerException на линии, где я пытаюсь установить текст в кнопке.

ответ

0

Объявите интерфейс во Фрагменте и реализуйте интерфейс в действии.

Вызовите интерфейс через обратный вызов во Фрагменте при нажатии кнопки. У вас может быть открытая функция во Фрагменте для обновления TextView, поэтому деятельность напрямую вызывает функцию для обновления текста.

Что-то вроде этого

public class FragmentB extends Fragment implements onClickListener{ 
ClickOnB listener; 
public void setOnFragmentBClickListener(ClickOnB listener){ 
this.listener = listener; 

} 

@Override 

public void onClick(View v){ 
//stringMessage is a `String` you will pass to the activity to update its `TextView` 
listener.onClickOnB(stringMessage); 
} 

interface ClickOnB{ 
public void onClickOnB(String message); 
} 

} 

и активность

public class MainActivity extends Activity implements ClickOnB{ 
@Override 
protected onCreate(Bundle savedInstanceState){ 

//Get a reference of `Fragment` B somewhere in your code after you added it dynamically and set the listener. 
((FragmentB)getFragmentManager().findFragmentByTag("FragmentB")).setOnFragmentBClickListener(this); 

} 

@Override 
public void onClickOnB(String message){ 

//Set the text to the `TextView` here (I am assuming you get a reference of the `TextView` in onCreate() after inflating your layout. 

mTextView.setText(message); 

} 
} 

для более подробной информации:

update TextView in fragment A when clicking button in fragment B

+0

Я не хочу устанавливать текст при нажатии кнопки. Я хочу установить текст при создании активности. Кроме того, у меня есть функция, которую я вызываю для обновления текста, но он не работает. Я прочитал этот вопрос и ответы, и они не работали для меня. В моем коде есть что-то не так. –

0

Попробуйте code-

getSupportFragmentManager().beginTransaction().replace(R.id.myProfileActionButtonsHolder, new MyProfileActionButtonsFragment(),"your_tag").commit(); 
MyProfileActionButtonsFragment fragment = getSupportFragmentManager().findFragmentByTag("your_tag"); 
if(null!=fragment){ 
fragment.setBMyProfileSettingsText("asd"); 
} 

желающий это работает.

+0

Я сделал это, и на этот раз я не получил NPE, и приложение не сработало, но текст не был установлен на «asd». Я думаю, что что-то не так с моим кодом фрагмента ... –

+0

thats, потому что он проверяет, что либо фрагмент имеет значение null, либо нет? Конечно, фрагмент имеет нулевое значение, то есть код причины внутри if не выполняется. У меня та же проблема. Надеюсь, скоро мы найдем решение. –

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