android - 如何在dialogfragment内部类中调用适配器

标签 android android-asynctask android-fragments android-dialogfragment

我有一个DialogFragment,它在第一次启动应用程序时打开。用户选择一个值,然后将其存储为首选项,然后根据所选值填充 listview 数据。

问题是我的自定义 DialogFragment 是一个内部类,位于我的 MainActivity 中。我似乎无法在 onclick 内调用我的适配器(它用数据加载我的 listview)。

我尝试访问内部类中的适配器函数,但收到“静态”引用错误。同时,我尝试将我的适配器函数嵌入到类中,但这导致了相同的结果:

Cannot make a static reference to the non-static method

我尝试过一些技巧,但我知道有一种更好的标准方法可以做到这一点。任何帮助/建议将不胜感激。

下面列出了我的代码。

public class MainActivity extends ListActivity {

private Cursor lines;
private MetroSleepDb db;
private ListAdapter adapter;
public static final String PREFS_NAME = "METROSLEEP_PREFS";
public static int PREFS_CITY = 0;

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

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    boolean prefs_isset = settings.contains("DEFAULT_CITY");

    if(prefs_isset) {

        PREFS_CITY = settings.getInt("DEFAULT_CITY", 0);


    } else {

        chooseCityDialog();
        PREFS_CITY = settings.getInt("DEFAULT_CITY", 0);

    }

    Editor editor = settings.edit();
    editor.putInt("DEFAULT_CITY", PREFS_CITY);
    editor.commit();

}


public void setAdapters() {

    Toast.makeText(getApplicationContext(), "Preference set to: "+PREFS_CITY, Toast.LENGTH_LONG).show();

    db = new MetroSleepDb(this);
    lines = db.getLines(); // you would not typically call this on the main thread
    //ListView listView = (ListView) findViewById(R.id.li);
    adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, 
            lines, 
            new String[] {"line_id"}, 
            new int[] {android.R.id.text1}, 0);


    getListView().setAdapter(adapter);
    getListView().setOnItemClickListener(onAnswerClicked);

}


public String getItem(int pos) {

    Cursor c = (Cursor) adapter.getItem(pos);
    String value = c.getString(c.getColumnIndex("line_id"));
    return value;
}


private OnItemClickListener onAnswerClicked = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        String line_value = getItem(position);
        Intent intent = new Intent(MainActivity.this, ChooseStations.class);
        intent.putExtra("line", line_value);
        startActivity(intent);
    }

};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem  item) {
    switch (item.getItemId()) {
    case android.R.id.home:

        NavUtils.navigateUpFromSameTask(this);
        return true;

    case R.id.menu_settings:
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void chooseCityDialog() {

    DialogFragment newFragment = new DialogSetup();
    newFragment.setCancelable(false);
    newFragment.setRetainInstance(true);
    newFragment.show(getFragmentManager(), "citypref");


}


public static final class DialogSetup extends DialogFragment {
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.prompt_choose_city)
               .setCancelable(false) 
               .setInverseBackgroundForced(true)
               .setItems(R.array.Cities, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {

                       PREFS_CITY = which;

               }
        });

        return builder.create();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        // Do whatever
    }

}



@Override
protected void onStop(){
   super.onStop();

  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  //editor.putBoolean("silentMode", mSilentMode);

  settings.getInt("DEFAULT_CITY", PREFS_CITY);
  editor.commit();
}
}

最佳答案

I have tried accessing my adapter function in the inner class but I receive a "static" reference error. At the same time, I tried embedding my adapter function inside the class, but that resulted in the same:

DialogFragment中,您已经有了对Activity的引用,其中显示了Dialog,您可以使用它来访问适配器:

public void onClick(DialogInterface dialog, int which) {
      PREFS_CITY = which;
      MainActivity ma = (MainActivity) getActivity();
      // create a getter method in the MainActivity to access the adapter 
      // or whatever else you need
}

关于android - 如何在dialogfragment内部类中调用适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940572/

相关文章:

java - Android Firebase - 卡未在 RecyclerView 和 NullPointerException 中显示

android - 在通知区域中监听 "Dark Theme"切换并收到更改通知

java - 防止 Fragment detach() 之后 onProgressUpdate() 数据丢失

android - 如何将 Activity 代码更改为 fragment 代码?

java - 在android中使用fragment从选项卡获取数据

Android 使用 CamcorderProfile 捕捉慢动作视频

java - 如何在 `Fragment` 中以编程方式更改屏幕亮度

android - 当其他任务正在运行时,AsyncTask 永远不会完成

java - Android 中的 HTML 请求

java - Android:如何知道何时从fragment返回