Я новичок в Android и стараюсь учиться самостоятельно. Но мне сложно провести время с Фрагментами. Я создаю простое приложение для изучения фрагментов. Я думаю, это может показаться глупым, но я действительно не могу заставить это работать.
Все, что я хочу сделать, это нажать кнопку (buttonSayHi) в Fragment_One, Fragment_One следует заменить на Fragment_Two.
Я не уверен, когда вызывается код фрагмента и где я должен написать свой код для вызова второго фрагмента. Я получаю сообщение об ошибке: Не удалось запустить компонент Activity.
Однако код отлично работает, если я отбрасываю слушателя для кнопки, и фрагмент отображается в пределах действия.
Я провел значительное исследование, прочитал учебник по фрагментам на developer.android.com, а также учебник Lars Vogella. Я думаю, что мои понятия не ясны.
Любая помощь будет оценена.
Ниже приведен код:
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayoutFragmentContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editTextPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="@+id/buttonSayHi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Say Hi"
android:onClick="onButtonClicked"/>
</LinearLayout>
fragment_two.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="I will say Hi!" />
</LinearLayout>
MainActivity.java
package com.example.fragmenttutorial;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
public class MainActivity extends Activity{
View view;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fragmentOne = new FragmentOne();
fragmentTransaction.add(R.id.frameLayoutFragmentContainer, fragmentOne);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
protected void onButtonClicked()
{
if(view.getId() == R.id.buttonSayHi){
Fragment fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
FragmentOne.java
package com.example.fragmenttutorial;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment{
View view;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
// protected void onButtonClicked()
// {
// if(view.getId() == R.id.buttonSayHi){
// Fragment fragmentTwo = new FragmentTwo();
//
// fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
// fragmentTransaction.addToBackStack(null);
//
// fragmentTransaction.commit();
//
// }
//
// }
}
Я прокомментировал код щелчка в фрагменте. Я также попытался реализовать onClickListener в фрагменте.
FragmentTwo.java
package com.example.fragmenttutorial;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
return view;
}
}
EDIT: я удалил строку android: onClick = "onButtonClicked" из моего кода в XML. И отредактировал следующие файлы, но он все еще не работает. Можете ли вы, ребята, предоставить мне рабочий пример без андроида: onClick = "onButtonClicked".
MainActivity.java
package com.example.fragmenttutorial;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
public class MainActivity extends Activity{
View view;
Fragment fragmentOne;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentOne = new FragmentOne();
fragmentTransaction.add(R.id.frameLayoutFragmentContainer, fragmentOne);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
FragmentOne.java
package com.example.fragmenttutorial;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentOne extends Fragment implements OnClickListener{
View view;
Fragment fragmentTwo;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
buttonSayHi.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Спасибо за ваши ценные предложения.