Как вызвать класс как действие, когда класс расширяет LinearLayout - PullRequest
0 голосов
/ 17 июня 2020

, как сказано в моем заголовке, я здесь с проблемой в Android studio (JAVA) с моим приложением, как вызвать класс как Activity, когда класс расширяет LinearLayout?

Мой класс: public class CustomCalendar extends LinearLayout {

Мой код, в котором я пытаюсь его вызвать:

 Intent customCalendar = new Intent(MainActivity.this, CustomCalendarActivity.class);
 startActivity(customCalendar);

Я пытался сделать это:

 public class CustomCalendarActivity extends AppCompatActivity {


    CustomCalendar customCalendar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        customCalendar = (CustomCalendar) findViewById(R.id.kalendoriaus_virsus);
        customCalendar.SetUpCalendar();
    }
}

Мой cra sh это:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.kalendorius.CustomCalendar.SetUpCalendar()' on a null object reference
        at com.example.kalendorius.MainActivity$2.onClick(MainActivity.java:75)

75 Строка:

 startActivity(customCalendar);

Как я настраиваю свой календарь:

Мой календарь. xml :

<?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:id="@+id/kalendoriaus_virsus"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/soft_blue_green"
        android:orientation="horizontal"
        android:paddingTop="8dp"
        android:paddingBottom="8dp">

        <ImageButton
            android:id="@+id/atgalBtn"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_margin="10dp"
            android:background="@drawable/back" />

        <TextView
            android:id="@+id/dabartineData"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:layout_weight="3"
            android:gravity="center"
            android:text="Data"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:textStyle="bold" />

Это всего лишь битовый код, в котором я использую этот kalendorius_virsus.

DONE. Я выясняю, в чем проблема. Я просто забыл сгенерировать конструктор базы данных: D Спасибо всем, кто пытался помочь.

Ответы [ 2 ]

2 голосов
/ 18 июня 2020

Проблема в customCalendar = (CustomCalendar) findViewById (R.id.kalendoriaus_virsus);

GroupView LinearLayout с идентификатором kalendorias_virsus в календарях. xml не является CustomCalendar, поэтому всегда возвращается значение null.

Вам необходимо понять, как правильно использовать общий вид

basi c пример CustomView ->

public class CustomView extends LinearLayout {

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View view =  LayoutInflater.from(getContext()).inflate(
                R.layout.costum, null);

        this.addView(view);
    }

    public void setCustomText(String text){
        TextView textview = (TextView) findViewById(R.id.textViewId);
        textview.setText(text);
    }
}

пользовательский макет. xml ->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textViewId"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/app_name"
        android:gravity="center">

    </TextView>
</LinearLayout>

активность. xml ->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.example.myapplication.CustomView
        android:id="@+id/customViewId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

Класс MainActivity ->

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomView customView = findViewById(R.id.customViewId);
        customView.setCustomText("Welcome ");
    }
}
0 голосов
/ 18 июня 2020

В вашем коде много ошибок. Нам все еще нужна дополнительная информация, чтобы определить, почему вы получаете NullPointerException (NPE) в методе MainActivity.onClick(). Однако это обязательно будет cra sh:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    customCalendar = (CustomCalendar) findViewById(R.id.kalendoriaus_virsus);
    customCalendar.SetUpCalendar();
}

, потому что customCalendar будет null, потому что вы не звонили setContentView() перед тем, как позвонить findBiewById().

Вы необходимо добавить

    setContentView(R.layout.XXXXXX);

, прежде чем звонить findViewById(). XXXXXX выше должно быть именем вашего файла макета XML (без расширения файла .xml).

...