-2

我想從strings.xml文件中爲列表視圖使用某些字符串作爲項目的名稱,但在部署期間,我的應用程序無法運行。我已經在互聯網的許多領域尋找相關教程,但他們都只是顯示了硬編碼的字符串。有誰知道我的代碼有什麼問題,以及如何使用字符串修復它,而不是硬編碼?未將字符串分配到列表視圖項

public class FragmentLineChooserList extends android.support.v4.app.Fragment { 

     ListView list_linechooser; 

     String[] listContent = { 
       getResources().getString(R.string.item_0), 
       getResources().getString(R.string.item_1), 
       getResources().getString(R.string.item_2) 
     }; 

     private boolean mTwoPane; 

     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
      View v = inflater.inflate(R.layout.fragment_line_chooser_list, container, false); 

      list_linechooser = (ListView)v.findViewById(R.id.list_linechooser); 
     MyColoringAdapter adapter = new MyColoringAdapter(getActivity(),listContent); 
     list_linechooser.setAdapter(adapter); 
     ); 

     return v; 
    } 

    private class MyColoringAdapter extends ArrayAdapter<String> { 
     private final Context context; 
     private final String[] values; 

     public MyColoringAdapter(Context context, String[] values) { 
      super(context, R.layout.list_item, values); 
      this.context = context; 
      this.values = values; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      LayoutInflater inflater = (LayoutInflater) context 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      View rowView = inflater.inflate(R.layout.list_item, parent, false); 
      TextView textView = (TextView) rowView.findViewById(R.id.list_item); 
      textView.setText(values[position]); 
      int textColorId = R.color.white; // Default color 
      switch (position) { 
       case 0: 
        textColorId = R.color.red; break; 
       case 1: 
        textColorId = R.color.yellow; break; 
       case 2: 
        textColorId = R.color.green; break; 
      } 
      textView.setTextColor(getResources().getColor(textColorId)); 
      return rowView; 
     } 
    } 
} 
+0

'getActivity()getResources()的getString(R.string.item_0);'哪裏是你的'adapter'類? –

+0

@MD這不起作用 – MacaronLover

+0

你能告訴我你的問題是什麼?有任何錯誤?如果是,然後張貼它。 –

回答

2

不喜歡

String[] listContent = { 
      getActivity().getResources().getString(R.string.item_0), 
      getActivity().getResources().getString(R.string.item_1), 
      getActivity().getResources().getString(R.string.item_2) 
    }; 

onCreateView(...)

+1

好,非常感謝,現在可以工作。問題在於它不在'onCreateView(...)' – MacaronLover

+1

@MacaronLover喲歡迎。 –

相關問題