0

Я пытаюсь использовать фрагменты для программного изменения текста на экране. Для этого я настраиваю прослушиватель нажатий на текстовом представлении, а затем, если щелкнуть его, запустите диспетчер фрагментов, заменив текущий фрагмент на новый фрагмент. Однако это приводит к сбою моего приложения при его запуске.OnClickListener и фрагменты, вызывающие крах приложения

От чтения отчета об аварии кажется, что ошибка происходит на tv1.setOnClickLIstener ...

Наконец, Android Студия продолжает давать мне несоответствие типов, когда я использую фрагмент или фрагмент поддержки. Вот почему вы видите android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

Java код:

public class MainActivity extends AppCompatActivity { 


@Override 
protected void onCreate(final Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //begin transaction 
    android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 

    //replace the contents of the container with the new fragment 
    ft.replace(R.id.placeHolder, new SplashScreenFragment()); 

    ft.commit(); 


    TextView tv1 = (TextView) findViewById(R.id.whatIsHumanTrafficing); 
    tv1.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View view) { 
      android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 

      ft.replace(R.id.placeHolder, new whatIsHumanTrafficing()); 
      ft.commit(); 
     } 
    }); 

} 

} 

XML из activity_main:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
> 

<FrameLayout 
    android:id="@+id/placeHolder" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 


</FrameLayout> 

XML отображается до щелчка:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.piatt.worksafe.MainActivity" 
android:id="@+id/splashScreenId" 
> 


<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Work Safe!" 
    android:textSize="36sp" 
    android:layout_centerHorizontal="true" 
    android:paddingBottom="32dp" 
    android:id="@+id/title" 
    /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="What is Human Trafficing?" 
    android:layout_below="@+id/title" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:id="@+id/whatIsHumanTrafficing" 
    android:clickable="true" 

    /> 


<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="How do I get safe labor?" 
    android:layout_below="@+id/whatIsHumanTrafficing" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:id="@+id/howDoIGetSafeLabor" 
    /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="How do I check that my job/job offer is legal?" 
    android:layout_below="@+id/howDoIGetSafeLabor" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:gravity="center" 
    android:id="@+id/checkLegality" 
    /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="How can I get help?" 
    android:layout_below="@+id/checkLegality" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:id="@+id/getHelp" 
    /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="About us" 
    android:layout_below="@+id/getHelp" 
    android:layout_centerHorizontal="true" 
    android:textSize="16sp" 
    android:layout_alignParentBottom="true" 
    android:gravity="bottom" 
    android:id="@+id/aboutUs" 
    /> 



</RelativeLayout> 

XML, который будет отображаться после щелчка на текстовом:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Human Trafficing Is:" 
    android:textSize="36sp" 
    android:layout_centerHorizontal="true" 
    android:paddingBottom="32dp" 
    android:id="@+id/title" 
    android:layout_gravity="center" 
    /> 



<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Confiscation of travel documents" 
    android:layout_below="@+id/HTdescription1" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:id="@+id/HTdescription1" 
    android:layout_gravity="center" 


    /> 


<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Unregistered Labor" 
    android:layout_below="@+id/HTdescription1" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:id="@+id/HDdescription2" 
    android:layout_gravity="center" 

    /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Isolation from friends and family" 
    android:layout_below="@+id/HTdescription2" 
    android:layout_centerHorizontal="true" 
    android:textSize="24sp" 
    android:padding="16dp" 
    android:id="@+id/HDdescription3" 
    android:layout_gravity="center" 

    /> 



</LinearLayout> 

Фрагмент имени человеческой торговли людьми, что я пытаюсь надуть:

public class whatIsHumanTrafficing extends Fragment{ 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){ 
    //inflate the layout for this fragment 
    return inflater.inflate(R.layout.what_is_human_trafficing, container, false); 
} 

}

+0

отправьте свой xml здесь – Nikhil

+0

Возможно, я покончил с этим, но я включил соответствующий xml – Davep

+0

, есть ли какой-нибудь фрагмент с именем 'whatIsHumanTrafficing'? – Nikhil

ответ

0

Вы использовали activity_main в вашем MainActivity следующим образом

setContentView(R.layout.activity_main); 

и вы получаете доступ к whatIsHumanTrafficing назван TextView в том же MainActivity, который невозможен, если нет в activity_main и который находится в другом xml. Таким образом, вы получаете NullPointerException.

+0

Это имеет такой смысл. Должен ли я получить доступ к текстовому представлению из фрагмента «что такое человеческий трафик», поскольку он имеет ссылку на правильный макет? Затем запустите транзакцию фрагмента в этом фрагменте? – Davep

+0

@Davep. Вы можете получить доступ к «текстовому виду» тогда и только тогда, когда вы надули соответствующий «xml» – Nikhil

+0

. Мы получаем доступ к текстовому виду через его идентификатор. Это хранится в отдельном файле 'R.id.' ... Почему XML-файл должен быть завышен, чтобы знать, что это текстовое представление существует? – Davep

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