2013-11-22 6 views
0

제 생각을 용서해주십시오. 프로그래밍에있어 완전히 새로운 말입니다. 나는이 안드로이드 애플 리케이션에 사용자 정의 글꼴을 listview와 함께 추가하려고하고있다. 제가 비슷한 질문에 대한 답변에서이 코드를 복사 여기 질문 : Custom font for Android listviewListview에 사용자 정의 글꼴 추가

class CustomAdapter extends ArrayAdapter<CharSequence>{ 

    Context context; 
    int layoutResourceId;  
    CharSequence data[] = null; 
    Typeface tf; 

public CustomAdapter(Context context, int layoutResourceId, CharSequence[] data, String FONT) { 
    super(context, layoutResourceId, data); 
    this.layoutResourceId = layoutResourceId; 
    this.context = context; 
    this.data = data; 
    tf = Typeface.createFromAsset(context.getAssets(), FONT); 
} 

하지만이 코드 줄을 넣을 위치를 파악 사투를 벌인거야 :

listAdapter = new CustomAdapter(this, R.layout.custom_list_text, R.array.abra_hotel, 
"name_of_font.ttf"); 

내가하려고 아무리

public class MainActivity extends Activity { 



// XML node keys 
static final String KEY_TAG = "weatherdata"; // parent node 
static final String KEY_ID = "id"; 
static final String KEY_CITY = "city"; 
static final String KEY_TEMP_C = "tempc"; 
static final String KEY_TEMP_F = "tempf"; 
static final String KEY_CONDN = "condition"; 
static final String KEY_SPEED = "windspeed"; 
static final String KEY_ICON = "icon"; 

// List items 
ListView list; 
BinderData adapter = null; 
List<HashMap<String,String>> weatherDataCollection; 




@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    try { 


     DocumentBuilderFactory docBuilderFactory = 
DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); 
     Document doc = docBuilder.parse (getAssets().open("weatherdata.xml")); 

     weatherDataCollection = new ArrayList<HashMap<String,String>>(); 

     // normalize text representation 
     doc.getDocumentElement().normalize(); 

     NodeList weatherList = doc.getElementsByTagName("weatherdata"); 

     HashMap<String,String> map = null; 

     for (int i = 0; i < weatherList.getLength(); i++) { 

       map = new HashMap<String,String>(); 

       Node firstWeatherNode = weatherList.item(i); 

       if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){ 

        Element firstWeatherElement = (Element)firstWeatherNode; 
        //------- 
        NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID); 
        Element firstIdElement = (Element)idList.item(0); 
        NodeList textIdList = firstIdElement.getChildNodes(); 
        //--id 
        map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim()); 

        //2.------- 
        NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_CITY); 
        Element firstCityElement = (Element)cityList.item(0); 
        NodeList textCityList = firstCityElement.getChildNodes(); 
        //--city 
        map.put(KEY_CITY, ((Node)textCityList.item(0)).getNodeValue().trim()); 

        //3.------- 
        NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_TEMP_C); 
        Element firstTempElement = (Element)tempList.item(0); 
        NodeList textTempList = firstTempElement.getChildNodes(); 
        //--city 
        map.put(KEY_TEMP_C, ((Node)textTempList.item(0)).getNodeValue().trim()); 

        //4.------- 
        NodeList condList = firstWeatherElement.getElementsByTagName(KEY_CONDN); 
        Element firstCondElement = (Element)condList.item(0); 
        NodeList textCondList = firstCondElement.getChildNodes(); 
        //--city 
        map.put(KEY_CONDN, ((Node)textCondList.item(0)).getNodeValue().trim()); 

        //5.------- 
        NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED); 
        Element firstSpeedElement = (Element)speedList.item(0); 
        NodeList textSpeedList = firstSpeedElement.getChildNodes(); 
        //--city 
        map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim()); 

        //6.------- 
        NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON); 
        Element firstIconElement = (Element)iconList.item(0); 
        NodeList textIconList = firstIconElement.getChildNodes(); 
        //--city 
        map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim()); 

        //Add to the Arraylist 
        weatherDataCollection.add(map); 
      }  
     } 


     BinderData bindingData = new BinderData(this,weatherDataCollection); 

     // list.setCacheColorHint(Color.TRANSPARENT); 




     list = (ListView) findViewById(R.id.list); 

     Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>"); 

     list.setAdapter(bindingData); 

     Log.i("AFTER", "<<------------- After SetAdapter-------------->>"); 

     // Click event for single list row 
     list.setOnItemClickListener(new OnItemClickListener() { 

      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 

       switch (position) { 
       case 0: 
       Intent newActivity0 = new Intent(MainActivity.this, 
SecondActivity.class);  
       startActivity(newActivity0); 
       break;} 

       switch (position) { 
       case 1: 
       Intent newActivity1 = new Intent(MainActivity.this, 
ThirdActivity.class);  
       startActivity(newActivity1); 
       break; } 

       switch (position) { 
       case 2: 
       Intent newActivity2 = new Intent(MainActivity.this, 
FourthActivity.class);  
       startActivity(newActivity2); 
       break; } 

       switch (position) { 
       case 3: 
       Intent newActivity3 = new Intent(MainActivity.this, 
FifthActivity.class);  
       startActivity(newActivity3); 
       break; } 

       switch (position) { 
       case 4: 
       Intent newActivity4 = new Intent(MainActivity.this, 
SixthActivity.class);  
       startActivity(newActivity4); 
       break; } 

       switch (position) { 
       case 5: 
       Intent newActivity5 = new Intent(MainActivity.this, 
SeventhActivity.class);  
       startActivity(newActivity5); 
       break; } 

       switch (position) { 
       case 6: 
       Intent newActivity6 = new Intent(MainActivity.this, 
EighthActivity.class);  
       startActivity(newActivity6); 
       break; } 

       switch (position) { 
       case 7: 
       Intent newActivity7 = new Intent(MainActivity.this, 
NinthActivity.class);  
       startActivity(newActivity7); 
       break; } 

       switch (position) { 
       case 8: 
       Intent newActivity8 = new Intent(MainActivity.this, 
TenthActivity.class);  
       startActivity(newActivity8); 
       break; } 

       switch (position) { 
       case 9: 
       Intent newActivity9 = new Intent(MainActivity.this, 
EleventhActivity.class);  
       startActivity(newActivity9); 
       break; } 




     }}); 

    } 

    catch (IOException ex) { 
     Log.e("Error", ex.getMessage()); 
    } 
    catch (Exception ex) { 
     Log.e("Error", "Loading exception"); 
    } 
} 



@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 


} 


class CustomAdapter extends ArrayAdapter<CharSequence>{ 

    Context context; 
    int layoutResourceId;  
    CharSequence data[] = null; 
    Typeface tf; 

public CustomAdapter(Context context, int layoutResourceId, CharSequence[] data, String FONT) { 
    super(context, layoutResourceId, data); 
    this.layoutResourceId = layoutResourceId; 
    this.context = context; 
    this.data = data; 
    tf = Typeface.createFromAsset(context.getAssets(), FONT); 
} 

} 

} 
: 그것을 배치하는 것은, 그것은 오류가 발생합니다 ... 여기

내 MainActivity 클래스입니다 17,451,515,

BinderData 클래스 :

public class BinderData extends BaseAdapter { 



// XML node keys 
static final String KEY_TAG = "weatherdata"; // parent node 
static final String KEY_ID = "id"; 
static final String KEY_CITY = "city"; 
static final String KEY_TEMP_C = "tempc"; 
static final String KEY_TEMP_F = "tempf"; 
static final String KEY_CONDN = "condition"; 
static final String KEY_SPEED = "windspeed"; 
static final String KEY_ICON = "icon"; 


LayoutInflater inflater; 
ImageView thumb_image; 
List<HashMap<String,String>> weatherDataCollection; 
ViewHolder holder; 
public BinderData() { 
    // TODO Auto-generated constructor stub 
} 

public BinderData(Activity act, List<HashMap<String,String>> map) { 

    this.weatherDataCollection = map; 

    inflater = (LayoutInflater) act 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 


public int getCount() { 
    // TODO Auto-generated method stub //  
      return idlist.size(); 
    return weatherDataCollection.size(); 
} 

public Object getItem(int arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

public long getItemId(int position) { 
    // TODO Auto-generated method stub 
    return 0; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 

    View vi=convertView; 
    if(convertView==null){ 

     vi = inflater.inflate(R.layout.list_row, null); 
     holder = new ViewHolder(); 

     holder.tvCity = (TextView)vi.findViewById(R.id.tvCity); // city name 
     holder.tvWeather = (TextView)vi.findViewById(R.id.tvCondition); // city weather 
overview 
     holder.tvTemperature = (TextView)vi.findViewById(R.id.tvTemp); // city temperature 
     holder.tvWeatherImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image 

     vi.setTag(holder); 
    } 
    else{ 

     holder = (ViewHolder)vi.getTag(); 
    } 

     // Setting all values in listview 

     holder.tvCity.setText(weatherDataCollection.get(position).get(KEY_CITY)); 
     holder.tvWeather.setText(weatherDataCollection.get(position).get(KEY_CONDN)); 
     holder.tvTemperature.setText(weatherDataCollection.get(position).get(KEY_TEMP_C)); 

     //Setting an image 
     String uri = "drawable/"+ weatherDataCollection.get(position).get(KEY_ICON); 
     int imageResource = 
vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, 
vi.getContext().getApplicationContext().getPackageName()); 
     Drawable image = vi.getContext().getResources().getDrawable(imageResource); 
     holder.tvWeatherImage.setImageDrawable(image); 

     return vi; 
} 

/* 
* 
* */ 
static class ViewHolder{ 

    TextView tvCity; 
    TextView tvTemperature; 
    TextView tvWeather; 
    ImageView tvWeatherImage; 
} 



} 

ListAdapter 등급 :

class CustomListAdapter extends BaseAdapter{ 

LayoutInflater inflater=null; 

int count=0; 
String[] List; 
Context context; 
public CustomListAdapter(Context c,String[] list){ 

    List = list; 
    count = list.length; 
    context=c; 

    inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

} 

    // TODO Auto-generated constructor stub 

@Override 
public int getCount() { 
    // TODO Auto-generated method stub 
    return count; 
} 

@Override 
public Object getItem(int position) { 
    // TODO Auto-generated method stub 
    return position; 
} 

@Override 
public long getItemId(int postion) { 
    // TODO Auto-generated method stub 
    return postion; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // TODO Auto-generated method stub 
    View view = convertView; 
    view = inflater.inflate(R.layout.list_row, null); 
    TextView TextofList = (TextView) view.findViewById(R.id.tvCity); 
    float textsize = (float) 15.0; 
    TextofList.setTextSize(textsize); 
    TextofList.setText(List[position]); 
    return view; 
} 

} 
+1

도움이 될 것입니다 그냥'BinderData' 어댑터에 폰트 코드를 넣으세요. 당신이 사용하고있는 어댑터 인 것 같습니까? –

+0

빠른 답장을 보내 주셔서 감사합니다. 나는 코드를 복사하고 그것을 바로 위에 두는 시도 : LayoutInflater inflater; BinderData 클래스에 있지만 위의 코드 줄에 구문 오류가 나타납니다 ... – user2881473

답변

0

는 사용자 지정 ArrayAdapter와를 작성해야합니다. 먼저 tutoria을 확인한 다음 어댑터의 항목 글꼴을 변경하십시오. 목록을 사용자 정의 할 수

+0

Thanks Sergio. 자습서를 검토하고 사용자 정의 ArrayAdapter를 작성해 봅니다. – user2881473

1

사용이 클래스 ... 또한

class CustomListAdapter extends BaseAdapter{ 

    LayoutInflater inflater=null; 

    int count=0; 
    String[] List; 
    Context context; 
    public CustomListAdapter(Context c,String[] list){ 

     List = list; 
     count = list.length; 
     context=c; 

     inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    } 
    @Override 
    public int getCount() { 
     // TODO Auto-generated method stub 
     return count; 
    } 

    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return position; 
    } 

    @Override 
    public long getItemId(int postion) { 
     // TODO Auto-generated method stub 
     return postion; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // TODO Auto-generated method stub 
     View view = convertView; 
     view = inflater.inflate(R.layout.row, null); 
     TextView TextofList = (TextView) view.findViewById(R.id.tv_list); 
     float textsize = 15.0; 
        TextofList.setTextSize(textsize); 
        TextofList.setText(List[position]); 
     return view; 
    } 

} 

및 활동 클래스에 아래 줄을 추가 ....

public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
      String[] list = {"abc","cde,","add",,"cde,","add",,"cde,","add"}; 
    ListView listv= (ListView) findViewById(R.id.listview); 

CustomListAdapter adapter = new CustomListAdapter(this,list); 
listv.setAdapter(adapter); 
}//end of OnCreat() 
}//end of mainactivty 

희망이 당신에게

+0

고맙습니다. ListAdapter라는 새로운 클래스를 만들고 거기에 코드를 복사했습니다 (편집 된 원래 게시물 참조). 하지만 코드를 넣으려고하면 :'CustomListAdapter adapter = new CustomListAdapter (this, list); listview.setAdapter (어댑터); '내 MainActivity 클래스에서 오류가 발생합니다 ... – user2881473

+0

어떤 오류가 발생합니까? –

+0

솔직히 말해서, MainActivity 클래스에 코드 라인을 어디에 둘 것인지 정확히 확신 할 수 없습니다. 나는 그것을 직접적으로 아래에 두는 것을 시도했다 : List > weatherDataCollection; 하지만 거기에 넣을 때 다음과 같은 오류가 발생합니다 : 레드 라인 필드의 이름을 바꿀 제안과 함께 어댑터 아래에 나타납니다 또한 redline 아래에 나타납니다 : 새 CustomListAdapter (this, list). 나는 그것을 onCreateOptionsMenu 메소드에 넣으려고했지만 새로운 customListAdapter (this, list)와 redline 아래에 빨간색 선이 생겼다. listview. – user2881473