Android Zugriff auf view von MainActivity

RezaScript

Bekanntes Mitglied
Hallo,

In MainActivity habe ich einen Knopf. Wenn ich darauf drucke, öffnet sich ein Dialog. Für den Dialog habe ich folgende Klasse erstellt:

Java:
public class Popup extends DialogFragment {
    private final int _layout;

    @SuppressLint("ValidFragment")
    public Popup(int layout) {
        _layout = layout;
    }

    @SuppressLint({"ClickableViewAccessibility", "ResourceType"})
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View view =  inflater.inflate(_layout, container, false);
        if (_layout == R.layout.fragment_dialog) {
        ...

In meinem Dialog habe ich auch einen Knopf und wenn ich da drauf klicke, möchte ich den Background vom MainActivity-Knopf ändern.

Wie kann ich also von meiner Klasse aus auf view von MainActivity zugreifen?
 

Jw456

Top Contributor
Du brauchst den Context der Activity.
Entweder gibst du ihn der Methode aus deiner anderen Klasse mit .

Oder du übergibst ihn beim erzeugen der Instanz deiner Klasse an den Kostrucktor.
Machst also einen Kostrucktor der den Context erwartet und den speicherst du in einer Instanzvariablen in der Klasse.
 

RezaScript

Bekanntes Mitglied
Und was soll ich dann mit dem Context anfangen?

Ich hab's mal so probiert:
Java:
private Context mContext;

@SuppressLint("ValidFragment")
public Popup(int layout) {
    _layout = layout;
}

public Popup(Context context, int layout) {
    mContext = context;
    _layout = layout;
}

Und so versuche ich den Context einzusetzen:
Java:
mContext.findViewById(R.id.dialog).setBackground(ContextCompat.getDrawable(getContext(), R.drawable.button_yellow));
Bekomme aber die Fehlermeldung: Cannot resolve method 'findViewById' in 'Context'
 

Jw456

Top Contributor
zeige alles nicht nur diese Stücken .
die kommplette Klasse bitte

eigentlich
Java:
mContext.getApplicationContext().findViewById(R.id.dialog) .....
 
Zuletzt bearbeitet:

RezaScript

Bekanntes Mitglied
Java:
@SuppressLint("ValidFragment")
public class Popup extends DialogFragment {
    private final int _layout;
    private final Dialog mDialog = new Dialog();
    public boolean dialogIsActive = false;
    private Context mContext;

    @SuppressLint("ValidFragment")
    public Popup(int layout) {
        _layout = layout;
    }

    public Popup(Context context, int layout) {
        mContext = context;
        _layout = layout;
    }

    @SuppressLint({"ClickableViewAccessibility", "ResourceType"})
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View view =  inflater.inflate(_layout, container, false);

        // Display fragment_dialog
        if (_layout == R.layout.fragment_dialog) {
            // Toggle the listener
            Button cta = view.findViewById(R.id.dialogCta);
            cta.setOnClickListener(v -> {
                if (!dialogIsActive) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (mDialog.hasRecordPermission(getContext())) {
                            mDialog.startService(getContext());
                            cta.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.button_red));
                            cta.setText(R.string.dialog_do_not_listen);
                            cta.setTextSize(17);
                            mContext.findViewById(R.id.dialog).setBackground(ContextCompat.getDrawable(getContext(), R.drawable.button_red));
                            dialogIsActive = true;
                        }
                    }
                }
                else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        mDialog.stopTheService(getContext());
                        cta.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.button_yellow));
                        cta.setText(R.string.dialog_listen);
                        mContext.findViewById(R.id.dialog).setBackground(ContextCompat.getDrawable(getContext(), R.drawable.button_yellow));
                        dialogIsActive = false;
                    }
                }
            });
        }
        return view;
    }
}
 

Robertop

Bekanntes Mitglied
Die "findViewById" Methode gehört nicht zur Context-Klasse, sondern zur View-Klasse, wenn mich nicht alles täuscht. Eigentlich dürfte die IDE dir die gar nicht vorschlagen.

Probier es mal hiermit:
Java:
requireActivity().findViewById(R.id.dialog)....
 

Jw456

Top Contributor
Java:
public class test {

     Activity mActivity;
     Context  mContext;

    public test(Activity activity,Context context) {
        this.mActivity = activity;
        this.mContext = context;
    }

    public void mtest(){
        mActivity.findViewById(R.id.dialog));
        ((Activity)mContext).findViewById(R.id.dialog));
    }
}

etweder du die Activity oder den Context.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
W onViewCreated blockiert Session Zugriff gegensatz zu onCreateView? Fragment Android & Cross-Platform Mobile Apps 25
J Android Zugriff auf eine Datei, diese von einer anderen App erstellt wurde? Android & Cross-Platform Mobile Apps 11
M Zugriff auf Helligkeitsregler von Handy? Android & Cross-Platform Mobile Apps 17
C Zugriff auf die Position eines String- bzw Spinner-Arrays Android & Cross-Platform Mobile Apps 1
E Wie erhalte ich Zugriff auf das Microfon? (Android Studio) Android & Cross-Platform Mobile Apps 9
B Android Kein Zugriff auf Telefonspeicher (Android 6) Android & Cross-Platform Mobile Apps 1
N Zugriff auf TextView in ListItem via ButtonClick Android & Cross-Platform Mobile Apps 4
K Android Zugriff auf FTP-Server Android & Cross-Platform Mobile Apps 1
S Android Zugriff auf Bilder im Telefonspeicher + Galeriedarstellung Android & Cross-Platform Mobile Apps 5
N Android Zugriff auf PlayStore im Abgesicherten Modus verhindern Android & Cross-Platform Mobile Apps 2
L Zugriff auf entfernten mySQL-Server via Android Android & Cross-Platform Mobile Apps 4
T Android Reflection zugriff auf setFocusableInTouchMode Android & Cross-Platform Mobile Apps 5
L Android Zugriff aus unbound Service auf Preferences Android & Cross-Platform Mobile Apps 2
H Smartphone (Front-)Kamera-Zugriff per Website Android & Cross-Platform Mobile Apps 6
S Android Zugriff auf FTP Server Android & Cross-Platform Mobile Apps 7
S Android Zugriff auf Website fuers Infos Android & Cross-Platform Mobile Apps 2
C Java ME Kein Java Zugriff auf Samsung! Android & Cross-Platform Mobile Apps 5
R Java ME mit Zugriff auf Adressbuch / Kalender Android & Cross-Platform Mobile Apps 3
H FileConnection: Frage nach Dateisystem-Zugriff unterdrücken Android & Cross-Platform Mobile Apps 5
1 zugriff auf handy-microfon Android & Cross-Platform Mobile Apps 2
H Zugriff auf XML/DB oder aehnliches Android & Cross-Platform Mobile Apps 3
G Zugriff auf den gesamten Bildschirm bei PDAs Android & Cross-Platform Mobile Apps 8
W Zur Laufzeit erstelltes MenuItem an eine View binden Android & Cross-Platform Mobile Apps 1
W Bild aus dem Internet in View bzw. ImageView laden (Fragment) Android & Cross-Platform Mobile Apps 2
J View Breite/Höhe bestimmen Android & Cross-Platform Mobile Apps 4
B Android In einem View der ersten Activity zweite anzeigen Android & Cross-Platform Mobile Apps 2
S Dynamische EditText View eingaben in Datenbank speichern Android & Cross-Platform Mobile Apps 0
V PopUp in gleicher View anzeigen Android & Cross-Platform Mobile Apps 1
M Android Suche Activity/View Namen Android & Cross-Platform Mobile Apps 1
R Android Warum (View view)? Android & Cross-Platform Mobile Apps 4
J Android neue View mit OnTouchListener Android & Cross-Platform Mobile Apps 0
B Eigene View xml-Layout einbinden Android & Cross-Platform Mobile Apps 1
R Problem mit View in ScrollView Android & Cross-Platform Mobile Apps 6
R Android Android.view Serializable ? Android & Cross-Platform Mobile Apps 3
M Android View zu View hinzufügen Android & Cross-Platform Mobile Apps 4
M Activity wechseln aus List View mit Android & Cross-Platform Mobile Apps 2
M Suche Name von View Komponente Android & Cross-Platform Mobile Apps 10
G canvas in view anzeigen Android & Cross-Platform Mobile Apps 10
G Fehlermeldung: "No XML content. Please add a root view or layout to your documet." Android & Cross-Platform Mobile Apps 7
E Android View zur Laufzeit hinzufügen Android & Cross-Platform Mobile Apps 4
N neuen view öffnen Android & Cross-Platform Mobile Apps 13
J id's von view komponenten werden nicht gefunden Android & Cross-Platform Mobile Apps 2
C Panel/View für Android Android & Cross-Platform Mobile Apps 3
tfa Android Layout-Probleme: View programmatisch erweitern (addContentView) Android & Cross-Platform Mobile Apps 7
G Dynamische View Inhalt -> Lagesensor Android & Cross-Platform Mobile Apps 3
H Android Nullpointer Exception bei Methodenaufruf durch MainActivity Android & Cross-Platform Mobile Apps 3
L Eingaben in der MainActivity einem Service übergeben Android & Cross-Platform Mobile Apps 0
L Android App ohne MainActivity Android & Cross-Platform Mobile Apps 3

Ähnliche Java Themen

Neue Themen


Oben