Używanie getResources () w klasie non-activity

Próbuję użyć metody getResources w klasie nieaktywnej. Jak uzyskać odniesienie do obiektu "resources", aby uzyskać dostęp do pliku XML przechowywanego w folderze resources?

Przykład:

XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
Author: Brian Tompsett - 汤莱恩, 2011-10-05

12 answers

Będziesz musiał przekazać context obiekt do niego. Albo this Jeśli masz odniesienie do klasy w activty, albo getApplicationContext()

public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        RegularClass regularClass = new RegularClass(this);
    }
}

Następnie możesz użyć go w konstruktorze (lub ustawić na zmienną instancji):

public class RegularClass(){
    private Context context;

    public RegularClass(Context current){
        this.context = current;
    }

    public findResource(){
        context.getResources().getXml(R.xml.samplexml);
    }
}

Gdzie konstruktor przyjmuje Context jako parametr

 153
Author: LuckyLuke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-17 13:14:41

To nie jest dobry pomysł, aby przekazać Context obiekty wokół. To często prowadzi do wycieków pamięci. Sugeruję, żebyś tego nie robił. Zrobiłem wiele aplikacji na Androida bez konieczności przekazywania kontekstu do klas innych niż aktywność w aplikacji. Lepszym pomysłem byłoby zdobycie zasobów, do których potrzebujesz dostępu, będąc w Activity lub Fragment, i trzymanie ich w innej klasie. Następnie możesz użyć tej klasy w innych klasach w aplikacji, aby uzyskać dostęp do zasobów, bez konieczności przechodzenia wokół Context obiektów.

 37
Author: Jason Crosby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-28 18:33:12

Jest jeszcze jeden sposób bez tworzenia obiektu. Sprawdź numer referencyjny . Dzięki za @ cristian. Poniżej dodaję kroki, które wymienione w powyższym odnośniku. Dla mnie nie lubię tworzyć do tego obiektu i dostępu. Więc próbowałem uzyskać dostęp do getResources() bez tworzenia obiektu. Znalazłem ten post. Więc pomyślałem, że dodam to jako odpowiedź.

Wykonaj kroki, aby uzyskać dostęp do getResources() w klasie non activity without passing a context za pośrednictwem obiektu.

  • Utwórz podklasę Application, na przykład public class App extends Application {. Zapoznaj się z kodem obok kroków.
  • ustaw atrybut android:name twojego znacznika <application> w AndroidManifest.xml, aby wskazywał na nową klasę, np. android:name=".App"
  • w metodzie onCreate() instancji aplikacji zapisz swój kontekst (np. this) do statycznego pola o nazwie app i utwórz statyczną metodę, która zwróci To pole, np. getContext().
  • teraz możesz użyć: App.getContext() kiedy tylko chcesz kontekstu, a następnie możemy użyć App.getContext().getResources(), aby uzyskać wartości z zasoby.

Tak powinno wyglądać:

public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }
}
 15
Author: Mahendran Sakkarai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:25:54

Oto moja odpowiedź:

public class WigetControl {
private Resources res;

public WigetControl(Resources res) 
{
    this.res = res;
}

public void setButtonDisable(Button mButton)
{
    mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
    mButton.setEnabled(false);
}

}

A wywołanie może wyglądać tak:

        WigetControl control = new WigetControl(getResources());
        control.setButtonDisable(btNext);
 5
Author: lizlalala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 08:37:34

Można to zrobić za pomocą

context.getResources().getXml(R.xml.samplexml);
 3
Author: A.R.Asha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-30 11:10:26

Możemy użyć kontekstu takiego jak ten spróbuj teraz, gdzie rodzicem jest ViewGroup.

Context context = parent.getContext();
 3
Author: Jaydip Umaretiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-31 06:07:41

Cóż, nie ma potrzeby mijania kontekstu i robienia tego wszystkiego...po prostu zrób to

Context context = parent.getContext();

Edit: gdzie rodzicem jest ViewGroup

 1
Author: Ankit Srivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-28 19:41:56

To zawsze działa dla mnie:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Nie związane z tym pytaniem, ale przykład użycia fragmentu, aby uzyskać dostęp do zasobów systemowych / działania w ten sposób:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);
 1
Author: Elroy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-21 12:49:02

W aplikacji tour guide podstawowego kursu Udacity na Androida użyłem pojęcia fragmentów. Utknąłem na chwilę doświadczając trudności, aby uzyskać dostęp do niektórych zasobów łańcuchowych opisanych w strings, plik xml. W końcu mam rozwiązanie.

To jest główna klasa aktywności

Pakiet com.przykład.android.tourguidekolkata;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
  //lines of code
   //lines of code
    //lines of code
    YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext()); 
    //lines of code
    // getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter 
}
}

Jest to klasa non Activity, która rozszerza FragmentPageAdapter

public class YourClass extends FragmentPagerAdapter {
private String yourStringArray[] = new String[4];
Context context;

public YourClass (FragmentManager fm, Context context)
{
    super(fm);
    this.context = context; // store the context of main activity
    // now you can use this context to access any resource 
    yourStringArray[0] = context.getResources().getString(R.string.tab1);
    yourStringArray[1] = context.getResources().getString(R.string.tab2);
    yourStringArray[2] = context.getResources().getString(R.string.tab3);
    yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
 {
 }
@Override
public int getCount() {
return 4;
}

@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
 1
Author: Satadru Saha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 08:42:53

W klasie simple deklaruje kontekst i pobiera dane z pliku z folderu res

public class FileData
{
      private Context context;

        public FileData(Context current){
            this.context = current;
        }
        void  getData()
        {
        InputStream in = context.getResources().openRawResource(R.raw.file11);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        //write stuff to get Data

        }
}

W klasie activity declare TAK

public class MainActivity extends AppCompatActivity 
{
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        FileData fileData=new FileData(this);
     }

}
 0
Author: sagar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-20 06:29:13

Jestem spóźniony, ale kompletne rozwiązanie;: Przykładowa Klasa, użyj kontekstu w następujący sposób: -

public class SingletonSampleClass {

    // Your cute context
    private Context context;
    private static SingletonSampleClass instance;

  // Pass as Constructor
    private SingletonSampleClass(Context context) {
        this.context = context;
    }

    public synchronized static SingletonSampleClass getInstance(Context context) {
        if (instance == null) instance = new SingletonSampleClass(context);
        return instance;
    }

//At end, don't forgot to relase memory
    public void onDestroy() {
       if(context != null) {
          context = null; 
       }
    }
}

Warning (Memory Leaks)

Jak to rozwiązać?

Opcja 1: zamiast przekazywać kontekst aktywności, np. Ten do klasy singleton, możesz przekazać applicationContext ().

Opcja 2: Jeśli naprawdę musisz użyć kontekstu aktywności, to kiedy aktywność zostanie zniszczona, upewnij się, że kontekst przekazany do klasy singleton jest ustawiony na null.

mam nadzieję, że to pomoże..∆∆∆∆

 0
Author: Amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-23 13:21:00

W swojej głównej aktywności:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(ResourcesHelper.resources == null){
             ResourcesHelper.resources = getResources();
        }
    }
}

ResourcesHelper:

public class ResourcesHelper {
    public static Resources resources;
}

Potem używaj go wszędzie

String s = ResourcesHelper.resources.getString(R.string.app_name);
 0
Author: Hamid fadili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-09 22:32:33