Я использую кнопку для вызова метода, который просто помещает ввод текста в текстовое окно. Всякий раз, когда я использую findViewById, он возвращает null.Android findViewById возвращает null
public void encode(View view){
TextView out = (TextView) view.findViewById(R.id.encoderout);
EditText in = (EditText) view.findViewById(R.id.encoderin);
out.setText(in.getText().toString());
out.setTypeface(font);
}
Мой XML здесь
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
>
<EditText android:id="@+id/encoderin"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:hint="Text to encode"/>
<Button android:id="@+id/encoderbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="encode"
android:text="Encode!"/>
</LinearLayout>
<TextView android:id="@+id/encoderout"
android:text="test"
android:layout_width="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"/>
</LinearLayout>
Почти каждый пост я мог бы найти сказал, что очистка проект помог решить эту проблему, но не в этом случае.
EDIT: ДОПОЛНИТЕЛЬНАЯ ИНФОРМАЦИЯ
Я использую фрагменты, и это мой фрагмент кода
public static class Encoder extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.encoder, container, false);
return view;
}
}
Это вызов в операцию из-за способа работы кнопок. Я могу называть методы find прекрасными в фрагменте, но не тогда, когда мне нужно вернуться к активности.
Я могу проверить, что представление не является нулевым, оно печатает отлично, когда в методе вызывается toString.
Решение: Никогда не осознавали, что мне нужно было использовать основной вид, подумал, что я ПОДДЕРЖИВАЮ, чтобы использовать представление кнопки. Я очень новичок в этом (начал сегодня), спасибо всем за вклад!
Вы вызывали 'setContentView()' перед вызовом 'findViewById'? –
paast весь ваш код активности, ваше представление равно null –
Вы уверены, что 'encode()' вызывается с помощью View, используя макет, который вы указали? –